I have a problem with spawning asynchronous subprocesses with timeout in Python 3.
What I want to achieve: I want to spawn multiple processes asynchronously without waiting for a results but I want also be assured that every spawned process will end within given timeout.
I have found similar problems here: Using module 'subprocess' with timeout and Asynchronous background processes in Python? but they does not solve my issue.
My code looks like this. I have Command class as suggested in 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()
and then when I want to spawn subprocesses:
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)
When I run this the output seems to wait for every command to spawn and end. I get
Thread started
Thread finished
Thread started
Thread finished
Thread started
Thread finished
Thread started
Thread finished
So my question is what I am doing wrong? Now I starting to wonder if it is possible to spawn a process and limit its execution by timeout.
Why I need this? The spawner script will run in cron. It will be executed every 10 minutes and it has to spawn about 20 subprocesses. I want to guarantee that every subprocess will end before the script will be run again from cron.