是否可以检测到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. 从命令提示符启动Visual Studio
- 4. 命令或脚本在Windows
- 5. 是否有一些jsp脚本可以打开Windows的命令提示符?
- 6. Clojure REPL无法在Windows命令提示符下启动
- 7. 未在命令提示符下运行的PHP脚本Windows 7
- 8. 在Windows命令提示符下处理多个perl脚本
- 9. 传递参数到Python脚本在Windows命令提示符
- 10. 以编程方式从命令提示符启动节点js脚本
- 11. 在windows上的命令提示符上运行lua脚本时输入输入
- 12. 为什么从Windows启动时运行程序而不是命令提示符?
- 13. 从Python控制Windows命令提示符
- 14. 从Windows命令提示符运行R
- 15. 检测mbstring是否启用PHP脚本
- 16. 检测单击或双击
- 17. 检查是否在Windows命令提示符下运行vs Cygwin python
- 18. Teradata - 在Unix上运行文件/脚本Linux命令提示符
- 19. Ruby在Windows命令提示符下
- 20. phonegap:是否有可能检测到从Javascript中双击滑动?
- 21. 双命令在命令提示符下运行程序
- 22. 从bash脚本中启动的命令检索错误代码
- 23. 转义双引号命令提示符
- 24. 是否有更好的Windows命令提示符?
- 25. jenkins-cli.jar mail命令从Windows命令提示符发送邮件
- 26. 从Windows命令提示符执行命令可执行文件
- 27. glassfish只能从netbeans IDE启动,而不能从命令提示符下启动
- 28. 双击启动Windows服务
- 29. 显示%(的Windows 10命令提示符)
- 30. Windows命令提示符:回显不带双引号的变量
聪明。你会怎么做? – grammar31 2009-02-17 21:36:14
从http://docs.python.org/library/os.html#os.getppid它似乎我可以得到进程ID,但不是名称。 – pkit 2009-02-17 21:42:35