system call that is killed after n seconds if not finished

Benjamin Kaplan benjamin.kaplan at case.edu
Mon Apr 16 11:33:51 EDT 2012


On Mon, Apr 16, 2012 at 10:51 AM, Jaroslav Dobrek
<jaroslav.dobrek at gmail.com> wrote:
>
> Hello,
>
> 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?
>
> Jaroslav

* Use subprocess instead of os.system. subprocess doesn't block
* run the process in another thread and have that thread do nothing
until the process is finished or a terminate flag gets set. If the
flag gets set, call terminate() on the Popen object.
* have the main thread call thread.join(5) on your new thread. After
that, set the terminate flag.



More information about the Python-list mailing list