2015-05-12 95 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

这似乎是一个很好的选择。我会尝试。非常感谢。 –

相关问题