如果任何一个子进程出错,则终止所有子进程

时间:2015-05-12 20:26:57

标签: python subprocess

我正在尝试同时运行两个子进程。我当前的程序看起来如果其中一个子进程有错误并终止,它将无法在1分钟后重新启动。它还需要等待另一个子进程失败,并且它们都会一起启动。我发现了一些关于如何杀死特定子进程的帖子,但我怎么能(1)如果一个子进程有错误,所有子进程将被终止并在1分钟后重新启动?或者(2)有错误的子进程可以在1分钟后重新启动而无需等待另一个正在运行的子进程?如果我改变

它会起作用吗?
proc.wait()

proc.kill()

在以下代码中?有没有更好的方法来处理它?<​​/ p>

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()       

1 个答案:

答案 0 :(得分:0)

如何运行循环来检查进程的状态?

这样的事情:

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