Note that there are some explanatory texts on larger screens.

plurals
  1. POasynchronous subprocess with timeout
    primarykey
    data
    text
    <p>I have a problem with spawning asynchronous subprocesses with timeout in Python 3.</p> <p>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.</p> <p>I have found similar problems here: <a href="https://stackoverflow.com/questions/1191374">Using module &#39;subprocess&#39; with timeout</a> and <a href="https://stackoverflow.com/questions/2496772">Asynchronous background processes in Python?</a> but they does not solve my issue.</p> <p>My code looks like this. I have Command class as suggested in <a href="https://stackoverflow.com/questions/1191374">Using module &#39;subprocess&#39; with timeout</a> :</p> <pre><code>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() </code></pre> <p>and then when I want to spawn subprocesses:</p> <pre><code>for system in systems: for service in to_spawn_system_info: command_str = "cd {0} &amp;&amp; python proc_ip.py {1} {2} 0 2&gt;&gt;{3}".format(home_dir, service, system, service_log_dir) command = Command(command_str) command.run(timeout=60) </code></pre> <p>When I run this the output seems to wait for every command to spawn and end. I get</p> <pre><code>Thread started Thread finished Thread started Thread finished Thread started Thread finished Thread started Thread finished </code></pre> <p>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.</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload