是否可以檢測到Python腳本是從命令提示符還是由用戶在Windows上的文件資源管理器中「雙擊」.py文件啓動?檢測腳本是否從命令提示符啓動或在Windows上「雙擊」
6
A
回答
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
的父進程。
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
相關問題
- 1. 如何檢測腳本是否從Django或命令提示符運行?
- 2. 命令提示符:檢查Windows服務是否啓動
- 3. 命令提示符腳本命令「cd」
- 4. 從命令提示符啓動Visual Studio
- 5. 命令或腳本在Windows
- 6. 從命令提示符運行PowerShell命令(無ps1腳本)
- 7. 從命令提示符運行docker命令與jenkins腳本
- 8. 是否有一些jsp腳本可以打開Windows的命令提示符?
- 9. Clojure REPL無法在Windows命令提示符下啓動
- 10. 在Windows命令提示符下處理多個perl腳本
- 11. 傳遞參數到Python腳本在Windows命令提示符
- 12. 未在命令提示符下運行的PHP腳本Windows 7
- 13. 如何從命令提示符啓動程序員記事本
- 14. 以編程方式從命令提示符啓動節點js腳本
- 15. 在windows上的命令提示符上運行lua腳本時輸入輸入
- 16. Windows命令提示符「啓動」命令在哪裏查找程序?
- 17. 在Windows提示符下使用一個啓動命令執行3個命令
- 18. 爲什麼從Windows啓動時運行程序而不是命令提示符?
- 19. 從Python控制Windows命令提示符
- 20. 從Windows命令提示符運行R
- 21. 從Windows命令提示符使用ssh
- 22. 檢測mbstring是否啓用PHP腳本
- 23. Windows腳本宿主錯誤時,腳本在命令提示符下運行
- 24. Windows Shell腳本「在這個時候是意外的。」在命令提示符
- 25. 檢測單擊或雙擊
- 26. 如何使用Python子進程啓動Windows命令提示符?
- 27. 如何使命令提示符快捷方式在啓動時運行腳本?
- 28. 檢查是否在Windows命令提示符下運行vs Cygwin python
- 29. 在Windows命令提示符中出現雙引號副作用
- 30. Teradata - 在Unix上運行文件/腳本Linux命令提示符
聰明。你會怎麼做? – grammar31 2009-02-17 21:36:14
從http://docs.python.org/library/os.html#os.getppid它似乎我可以得到進程ID,但不是名稱。 – pkit 2009-02-17 21:42:35