2016-06-07 218 views
2

我想知道如何检查程序是否使用python运行,如果没有运行它。我有2个python脚本,一个是监视另一个脚本的GUI。所以基本上如果第二个脚本出于某种原因崩溃,我希望重新开始。 P.S.我在Windows上使用python 3.4.2。检查程序是否正在运行

+0

谷歌四周,看到什么就是了pidfile,也许这将解决您的问题。 – Maciek

+0

这可能会帮助你:http://stackoverflow.com/questions/1632234/list-running-processes-on-64-bit-windows –

+0

'sudo apt-get install supervisor' – C14L

回答

5

该模块psutil可以帮助你。要列出所有进程乳宁的使用:如果这个过程中使用Python,像

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 

如果您在使用psutil.pids()的,你可以验证所有:

import psutil 

print(psutil.pids()) # Print all pids 

要访问过程的信息,使用

for pid in psutil.pids(): 
    p = psutil.Process(pid) 
    if p.name() == "python.exe": 
     print("Called By Python:"+ str(p.cmdline()) 

psutil的文档可在:https://pypi.python.org/pypi/psutil

编辑1

假设,如果脚本的名称是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") 
+0

我认为这不是默认的python库之一,或者我错了?如果是的话,我发现这个库https://pypi.python.org/pypi/psutil,你这个这个是对的吗? – Sande

+0

是的,你说得对,这个lib不是默认的lib,但你的链接是正确的,是一样的模块 – 2016-06-07 12:51:13

+0

另一个问题,我看到这反应在所有的python脚本作为python.exe,但我想检查单独的脚本不主要是有p.cmdline()行psutil – Sande

相关问题