Michele Petrazzo <michele.petra...@remove_me_unipex.it> 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 try: self.result = self.function(*args, **kwargs) success = True except: 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') True >>> ft.result 'f does this: foo' >>> ft.test() False >>> print ft.error Traceback (most recent call last): File "tester.py", 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 exec. Hope this helps, alex23 -- http://mail.python.org/mailman/listinfo/python-list