Python 检查程序是否以编程方式运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37678954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if program is running programmatically
提问by Sande
I was wondering how you could check if program is running using python and if not run it. I have two python scripts one is GUI which monitors another script.So basically if second script for some reason crashes I would like it start over.
我想知道如何检查程序是否正在使用 python 运行,如果没有运行它。我有两个 python 脚本,一个是监视另一个脚本的 GUI。所以基本上如果第二个脚本由于某种原因崩溃,我希望它重新开始。
n.b. I'm using python 3.4.2
on Windows.
nb 我python 3.4.2
在 Windows 上使用。
回答by
The module psutil can help you. To list all process runing use:
模块 psutil 可以帮助您。要列出所有正在运行的进程,请使用:
import psutil
print(psutil.pids()) # Print all pids
To access the process information, use:
要访问进程信息,请使用:
p = psutil.Process(1245) # The pid of desired process
print(p.name()) # If the name is "python.exe" is called by python
print(p.cmdline()) # Is the command line this process has been called with
If you use psutil.pids()
on a for, you can verify all if this process uses python, like:
如果psutil.pids()
在 for 上使用,则可以验证此过程是否使用 python,例如:
for pid in psutil.pids():
p = psutil.Process(pid)
if p.name() == "python.exe":
print("Called By Python:"+ str(p.cmdline())
The documentation of psutil is available on: https://pypi.python.org/pypi/psutil
psutil 的文档位于:https://pypi.python.org/pypi/psutil
EDIT 1
编辑 1
Supposing if the name of script is Pinger.py, you can use this function
假设脚本的名字是Pinger.py,你可以使用这个函数
def verification():
for pid in psutil.pids():
p = psutil.Process(pid)
if p.name() == "python.exe" and len(p.cmdline()) > 1 and "Pinger.py" in p.cmdline()[1]:
print ("running")