Timed execution in eval

George Sakkis george.sakkis at gmail.com
Fri Mar 7 22:43:48 EST 2008


On Mar 7, 11:12 am, alex.pedwyso... at gmail.com wrote:
> I have various bits of code I want to interpret and run at runtime in
> eval ...
>
> I want to be able to detect if they fail with error, I want to be able
> to time them, and I want to be able to stop them if they run too
> long.  I cannot add code to the eval'd strings that will help me
> accomplish this.
>
> Is there a good way to do this?  I have it figured out for perl
> but I'd rather use python if possible.
>
> Thanks for any assistance.

Check out these two recipes:

- Using signals: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871

- Using threads: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752

Note that neither is perfect; the first breaks if the timed code
overrides the alarm signal, while the second can't interrupt code that
doesn't release the GIL and doesn't actually kill the function after
the timeout.

I'd be rather surprised if the perl solution you figured out doesn't
have any issues.

George



More information about the Python-list mailing list