views:

63

answers:

2

I want to execute an external program in each thread of a multi-threaded python program.

Let's say max running time is set to 1 second. If started process completes within 1 second, main program capture its output for further processing. If it doesn't finishes in 1 second, main program just terminate it and start another new process.

How to implement this?

A: 

A nasty hack on linux is to use the timeout program to run the command. You may opt for a nicer all Python solution, however.

fmark
+2  A: 

You could poll it periodically:

import subprocess, time

s = subprocess.Popen(['foo', 'args'])
timeout = 1
poll_period = 0.1
s.poll()
while s.returncode is None and timeout > 0:
    time.sleep(poll_period)
    timeout -= poll_period
    s.poll()
if timeout <= 0:
    s.kill() # timed out
else:
    pass # completed

You can then just put the above in a function and start it as a thread.

Liquid_Fire