try except inside exec

alex23 wuwei23 at
Mon Jun 1 00:24:19 EDT 2009

Michele Petrazzo <michele.petrazzo at> wrote:
> 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?
> 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"]

Hello Michele,

>From your code, I'm not sure if you're aware that functions are
themselves objects within Python. You could avoid the use of exec
entirely by doing something like the following:

import traceback

class FuncTester(object):
  def __init__(self, function):
    self.function = function

  def test(self, *args, **kwargs):
    self.result, self.error = None, None
      self.result = self.function(*args, **kwargs)
      success = True
      self.error = traceback.format_exc()
      success = False
    return success

>>> def f(x): return 'f does this: %s' % x
>>> ft = FuncTester(f) # note that we're referring to the function directly
>>> ft.test('foo')
>>> ft.result
'f does this: foo'
>>> ft.test()
>>> print ft.error
Traceback (most recent call last):
  File "", line 10, in test
    self.result = self.function(*args, **kwargs)
TypeError: f() takes exactly 1 argument (0 given)

I think you'll find this approach to be a lot more flexible than using

Hope this helps,

More information about the Python-list mailing list