2009-02-17 31 views

回答

3

以下是如何獲取當前運行腳本的父進程ID和名稱的示例。如Tomalak所示,這可用於檢測腳本是從命令提示符還是通過在瀏覽器中雙擊啓動。

import win32pdh 
import os 

def getPIDInfo(): 
    """ 
    Return a dictionary with keys the PID of all running processes. 
    The values are dictionaries with the following key-value pairs: 
     - name: <Name of the process PID> 
     - parent_id: <PID of this process parent> 
    """ 

    # get the names and occurences of all running process names 
    items, instances = win32pdh.EnumObjectItems(None, None, 'Process', win32pdh.PERF_DETAIL_WIZARD) 
    instance_dict = {} 
    for instance in instances: 
     instance_dict[instance] = instance_dict.get(instance, 0) + 1 

    # define the info to obtain 
    counter_items = ['ID Process', 'Creating Process ID'] 

    # output dict 
    pid_dict = {} 

    # loop over each program (multiple instances might be running) 
    for instance, max_instances in instance_dict.items(): 
     for inum in xrange(max_instances): 
      # define the counters for the query 
      hq = win32pdh.OpenQuery() 
      hcs = {} 
      for item in counter_items: 
       path = win32pdh.MakeCounterPath((None,'Process',instance, None,inum,item)) 
       hcs[item] = win32pdh.AddCounter(hq,path) 
      win32pdh.CollectQueryData(hq) 

      # store the values in a temporary dict 
      hc_dict = {} 
      for item, hc in hcs.items(): 
       type,val=win32pdh.GetFormattedCounterValue(hc,win32pdh.PDH_FMT_LONG) 
       hc_dict[item] = val 
       win32pdh.RemoveCounter(hc) 
      win32pdh.CloseQuery(hq) 

      # obtain the pid and ppid of the current instance 
      # and store it in the output dict 
      pid, ppid = (hc_dict[item] for item in counter_items) 
      pid_dict[pid] = {'name': instance, 'parent_id': ppid} 

    return pid_dict 

def getParentInfo(pid): 
    """ 
    Returns a PID, Name tuple of the parent process for the argument pid process. 
    """ 
    pid_info = getPIDInfo() 
    ppid = pid_info[pid]['parent_id'] 
    return ppid, pid_info[ppid]['name'] 

if __name__ == "__main__": 
    """ 
    Print the current PID and information of the parent process. 
    """ 
    pid = os.getpid() 
    ppid, ppname = getParentInfo(pid) 

    print "This PID: %s. Parent PID: %s, Parent process name: %s" % (pid, ppid, ppname) 
    dummy = raw_input() 

當從命令運行提示此輸出:

此PID:148.父PID:4660,父進程名稱:在cmd

當在資源管理器雙擊開始此輸出:

此PID:1896.父PID:3788,父進程名稱:explorer

3

命令提示符啓動的腳本有一個名爲cmd.exe的父進程(或者在控制檯同時關閉的情況下不存在的進程)。

doubleclick-started腳本應該有一個名爲explorer.exe的父進程。

+0

聰明。你會怎麼做? – grammar31 2009-02-17 21:36:14

+0

從http://docs.python.org/library/os.html#os.getppid它似乎我可以得到進程ID,但不是名稱。 – pkit 2009-02-17 21:42:35

2

好問題。你可以做的一件事是在Windows中爲腳本創建一個快捷方式,並傳遞參數(使用快捷方式的Target屬性)來表示腳本是通過雙擊(在本例中爲快捷方式)啓動的。

7

如果從命令行運行,則會定義一個額外的環境變量'PROMPT'。

如果從資源管理器中點擊並不會暫停,如果在命令行中運行該腳本將暫停:

import os 

print 'Hello, world!' 

if not 'PROMPT' in os.environ: 
    raw_input() 

測試在Windows 7上使用Python 2.7

0

我把這個小功能(pybyebye() )就在我的一些程序中的return語句之前。我已經在我的臺式機和筆記本電腦的Windows 10下測試了它,並且它按照我的要求進行了測試,即只有在通過雙擊文件資源管理器中的程序啓動程序時,它纔會暫停等待用戶輸入。這可以防止臨時命令窗口在用戶這樣說之前消失。在Linux下,它什麼都不做。無論如何沒有傷害!同樣在Mac上。

## PYBYEBYE : 
def pybyebye (eprompt="PROMPT",efps="FPS_BROWSER_"): 
    "nice exit in Windows according to program launch from: IDLE, command, clix." 

## first examine environment (os & sys having been imported) : 
ui = None 
platform = sys.platform 
## print("os =",platform) 
if not platform.lower().startswith("win"): 
    return ui ## only relevant in windows 
fromidle = False 
launched = "Launched from" 
if sys.executable.endswith("pythonw.exe"): 
    fromidle = True ## launched from within IDLE 
envkeys = sorted(os.environ) 
prompter = eprompt in envkeys 
browser = False 
for ek in envkeys: 
    ## print(ek) 
    if ek.startswith(efps): 
     browser = True 
     break 
## next decide on launch context : 
if fromidle and not prompter: ## surely IDLE 
    ## print(launched,"IDLE") 
    pass ## screen won't disappear 
elif browser and not prompter: ## run with double click 
    ## print(launched,"File Explorer") 
    print("Press Enter to finish ....") ; ui=input() 
elif prompter and not fromidle: ## run from preexisting command window 
    ## print(launched,"Command Window") 
    pass ## screen won't disappear 
else: ## something funny going on, Mac or Linux ?? 
    print("launch mode undetermined!") 

return ui 
相關問題