system call that is killed after n seconds if not finished

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Mon Apr 16 11:34:13 EDT 2012


Jaroslav Dobrek <jaroslav.dobrek at gmail.com> writes:

> I would like to execute shell commands, but only if their execution
> time is not longer than n seconds. Like so:
>
> monitor(os.system("do_something"), 5)
>
> I.e. the command do_somthing should be executed by the operating
> system. If the call has not finished after 5 seconds, the process
> should be killed.
>
> How could this be done?

My system (linux) has a timeout command that does just this. Otherwise,
you may use subprocess.Popen to spawn the process, sleep for 5 seconds
in the parent, then use Popen.poll() to check whether the process has
finished, and finally Popen.kill() if it has not.

-- Alain.



More information about the Python-list mailing list