2016-06-07 217 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

相關問題