2015-05-12 22 views
0

我想同時運行兩個子進程。我目前的程序看起來像是一個子進程出錯並終止,1分鐘後它不能再次重新啓動。它需要等待另一個子進程失敗,並且它們都一起啓動。我發現了一些關於如何殺死特定子進程的帖子,但是我怎麼能(1)如果一個子進程有錯誤,所有的子進程會被終止並在1分鐘後再次重新啓動?或者(2)有錯誤的子進程可以在1分鐘後再次重新啓動,而無需等待另一個正在運行的子進程?如果我在下面的代碼更改終止所有子進程,如果任何一個子進程有錯誤

proc.wait() 

proc.kill() 

它是否行得通呢?有沒有更好的方法來處理它?

import sys 
import subprocess 
import os    
import time 

def executeSomething(): 
    # This setting is very important to avoid errors 
    os.environ['PYTHONIOENCODING'] = 'utf-8'  

    procs = [] 
    files = ["TwitterDownloader_1.py","TwitterDownloader_2.py"] 
    try: 
     for i in files: 
      proc = subprocess.Popen([sys.executable,i]) 
      procs.append(proc) 

     for proc in procs: 
      proc.wait() 
    except AttributeError: 
     print 'Attribute Error found and skiped' 
    time.sleep(61) 

while True: 
    executeSomething()  
+0

可能重複[?如何讓家長退出後,子進程死亡(https://stackoverflow.com/questions/284325/how-to-make-child- process-die-after-parent-exits/23401172#23401172) –

+0

看起來我需要定義父母和子程序,讓子程序發送信號告訴父母停止所有子程序? –

回答

-1

如何運行循環來檢查進程的狀態?

事情是這樣的:

for proc in procs: 
    if proc.poll() is not None: # it has terminated 
     # check returncode and handle success/failure 
+0

這似乎是一個很好的選擇。我會嘗試。非常感謝。 –

相關問題