How to use the exec statement
Alex Martelli
aleax at aleax.it
Mon Oct 7 12:31:06 EDT 2002
JB wrote:
...
> Well, I could preprocess the string that is given to exec. I
> am thinking about introducing '<---' instead of '=' anyway.
> Then only assignments, function calls and function
> definitions would be allowed.
You'll have to do a lot of special-purpose checks to
ensure e.g. that I don't do
raise('gotcha')
LOOKS LIKE a function call, but since 'raise' is a
keyword, it's actually a raise statement and it's going
to raise a string-exception:-).
> But even so, I cannot catch every error. But I could use
> except without a name, couldn't I? like in
Yes (sigh).
> def f(x,y):
> try:
> return x/y
> except:
> print 'error'
>
> Then if I split the string that is give to exec I can even
> tell in which line the error occured.
> Is this sensible?
Not really, but there's not much else you can do:-(.
You don't need to split the string - as part of the
traceback (which you can get inside the handler) you
get the line-number on which the exception was raised.
Alex
More information about the Python-list
mailing list