Re: Timed execution in eval
- From: "Guilherme Polo" <ggpolo@xxxxxxxxx>
- Date: Sat, 8 Mar 2008 09:16:41 -0300
2008/3/7, Steven D'Aprano <steve@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>:
On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote:
> I have various bits of code I want to interpret and run at runtime in
> eval ...
I hope that code doesn't contain any data coming from an untrusted user.
> I want to be able to detect if they fail with error,
That's what try...except blocks are for.
try:
x = eval('1 + 1 = 2')
except SyntaxError:
x = 3
> I want to be able to time them,
That's what the timeit module is for.
If you do time them, you will find that eval(expr) is MUCH MUCH slower
than just executing expr as normal.
>>> from timeit import Timer
>>> Timer('1+1').timeit()
0.25557518005371094
>>> Timer('eval("1+1")').timeit()
21.816912174224854
If you use eval() a lot, you will have a SLOW program.
> and I want to be able to stop them if they run too long.
That's tricky. As far as I know, the only way for a Python program to
stop an arbitrary calculation after a certain period of time it to run it
in a thread. You then monitor the elapsed time, and when the timer
expires, ask the thread to die. And hope it listens.
Or you could use setitimer (not available for now). I opened an issue
at roundup to add setitimer and getitimer wrappers to the signal
module.
It would be great if you could test on your platform. It was done for
py3k, but could easily be back ported to python 2.6.
http://bugs.python.org/issue2240
> I cannot add code to the eval'd strings that will help me accomplish
> this.
You can't? Why ever not?
Note: that's almost certainly the wrong way to solve your problem, but
I'm curious as to why you can't.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
--
-- Guilherme H. Polo Goncalves
.
- Follow-Ups:
- Re: Timed execution in eval
- From: castironpi
- Re: Timed execution in eval
- References:
- Timed execution in eval
- From: alex . pedwysocki
- Re: Timed execution in eval
- From: Steven D'Aprano
- Timed execution in eval
- Prev by Date: parralel downloads
- Next by Date: Writing Memory to File
- Previous by thread: Re: Timed execution in eval
- Next by thread: Re: Timed execution in eval
- Index(es):
Relevant Pages
|