try except inside exec

Carl Banks pavlovevidence at gmail.com
Fri May 29 23:58:03 CEST 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()
> """
>
> env = {}
> exec STR in env
> env["a_funct"]()
> print env["err"]
>
> 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




More information about the Python-list mailing list