try except inside exec

Carl Banks pavlovevidence at gmail.com
Fri May 29 18:20:00 EDT 2009


On May 29, 7:21 am, Michele Petrazzo
<michele.petrazzo at REMOVE_me_unipex.it> wrote:
> Hi all,
> I want to execute a python code inside a string and so I use the exec
> statement. The strange thing is that the try/except couple don't catch
> the exception and so it return to the main code.
> Is there a solution to convert or make this code work?
>
> Thanks,
> Michele
>
> My code:
>
> STR = """
> err = 0
> try:
>    def a_funct():
>      1/0
> except:
>    import traceback
>    err = traceback.format_exc()
> """

The exception isn't being raised because you haven't called the
function.  It's not an exception to define a function that does a
divide by zero, only to execute such a function.


> env = {}
> exec STR in env
> env["a_funct"]()

Here is where you call the function, thus the exception occurs here.


> print env["err"]

This line isn't actually being executed.  I'm not sure if you realize
that....

> My error:
>    File "tmp/test_exec.py", line 14, in <module>
>      env["a_funct"]()
>    File "<string>", line 5, in a_funct
> ZeroDivisionError: integer division or modulo by zero

In general you can't know ahead of time what exceptions a function
might raise, so what you are trying to do can't be done.  You have to
handle the exception at the point where it is called.


And from another post:
> My goal is to execute a function received from a third-part,

The only time it's not a gaping security hole to run code supplied by
a thrid-party as-is is if the program is running on the third-party's
own computer.

If you're execing code on your computer that you didn't write or
thoroughly verify yourself--and you're obviously not doing that--then
you might as well just post your password publicly and say, "have at
it evil hackers".


Carl Banks



More information about the Python-list mailing list