异步子我有产卵与超时异步子流程在Python 3与超时
我想达到什么问题:我想产卵多个进程异步无需等待结果,但我想也可以放心,每个产生的进程将在给定的超时内结束。
我在这里发现了类似的问题:Using module 'subprocess' with timeout和Asynchronous background processes in Python?但他们没有解决我的问题。
我的代码看起来像这样。我有一个命令类的建议在Using module 'subprocess' with timeout:
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout):
def target():
print('Thread started')
args = shlex.split(self.cmd)
self.process = subprocess.Popen(args, shell=True)
self.process.communicate()
print('Thread finished')
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print('Terminating process')
self.process.terminate()
thread.join()
,然后当我想产卵子流程:当我运行此输出似乎等待每个命令产卵和结束
for system in systems:
for service in to_spawn_system_info:
command_str = "cd {0} && python proc_ip.py {1} {2} 0 2>>{3}".format(home_dir,
service, system, service_log_dir)
command = Command(command_str)
command.run(timeout=60)
。我得到
Thread started
Thread finished
Thread started
Thread finished
Thread started
Thread finished
Thread started
Thread finished
所以我的问题是我做错了什么?现在我开始怀疑是否有可能产生一个进程并通过超时限制它的执行。
为什么我需要这个? spawner脚本将在cron中运行。它将每隔10分钟执行一次,它必须产生大约20个子进程。我想保证每个子进程都会在脚本从cron重新运行之前结束。
当我尝试这个解决方案时,它不会在超时后终止我的线程。我将超时设置为1秒,并在目标函数中添加time.sleep(1)。没有线程被终止。 – sebast26 2013-05-14 13:20:11
Hrmm。当target()退出时,线程应该终止。请记住,如上所述,如果过程正常退出而不超时,则不会得到打印输出。我会仔细观察一下,我可能忽略了一些东西。 – mshildt 2013-05-14 13:29:15
因此,如果线程在子进程完成之前终止,子进程将终止?这与unutbu说的相反。他说,“那么,即使你的线程完成后,你产生的每个子进程都将继续存在”。我还有一个印象,就是子进程会继续下去。 – b10hazard 2013-05-14 13:36:29