我在Python 3中使用异步子进程生成超时存在问题。
我的目标是:我想异步生成多个进程,而不等待结果,但我也想确保每个生成的进程都会在给定的超时时间内结束。
我在这里找到了类似的问题:Using module 'subprocess' with timeout 和 Asynchronous background processes in Python? ,但它们不能解决我的问题。
我的代码如下所示。我有一个命令类,如使用模块'subprocess' with timeout中建议的那样:
当我运行这个命令时,输出似乎等待每个命令的生成和结束。我得到:
我的目标是:我想异步生成多个进程,而不等待结果,但我也想确保每个生成的进程都会在给定的超时时间内结束。
我在这里找到了类似的问题:Using module 'subprocess' with timeout 和 Asynchronous background processes in Python? ,但它们不能解决我的问题。
我的代码如下所示。我有一个命令类,如使用模块'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
我的问题是我做错了什么?现在我开始怀疑是否可能生成一个进程并通过超时来限制其执行。
为什么我需要这个?生成器脚本将在cron中运行。它将每10分钟执行一次,并且必须生成约20个子进程。我希望保证每个子进程都会在下一次从cron运行脚本之前结束。
self.process.wait()
以使线程等待子进程完成,这样线程在子进程完成之前不会退出。然而,我的解决方案有些问题。我正在尝试解决它,但似乎无法正确运行进程...仍在研究中。 - mshildt