unhandled exception question

joshusdog at gmail.com joshusdog at gmail.com
Fri May 25 15:52:56 EDT 2007


I'm working on a test application that embeds the Python interpreter.
I have the following problem...

I've created my own interactive interpreter loop. Essentially, it
reads the command from the prompt and calls the following C code:

	PyObject* pMainModule = PyImport_AddModule("__main__");
	PyObject* pMainDictionary = PyModule_GetDict(pMainModule);
	PyObject* pObj = PyRun_String(pCommandText, Py_single_input,
pMainDictionary, pMainDictionary);

where pCommandText is the text entered by the user.

I also have the following Python functions defined:

	def Boo():
		raise Exception()

	def Foo():
		try:
			MyModule.SomeFunction()
		except Exception:
			print "goodbye"

MyModule.SomeFunction() is defined in C. All it does is call Boo()
with the following code:

	PyObject* pMainModule = PyImport_AddModule("__main__");
	PyObject* pMainDictionary = PyModule_GetDict(pMainModule);
	PyObject* pObj = PyRun_String("Boo()", Py_single_input,
pMainDictionary, pMainDictionary);

If it's at all relevent, I'm using Boost.Python to embed MyModule.

Now here's the problem: when I type "Foo()" at the prompt, it calls
Foo(), which calls MyModule.SomeFunction(), which calls Boo(), which
raises the exception. However, the exception doesn't get handled,
despite the try-except statement in Foo(). Even stranger, if I
manually enter the entire multi-line try-except statement at the
prompt (instead of simply calling Foo()), the exception is handled
properly and "goodbye" is printed to the screen.

What's going on here? Why is exception properly handled in the second
case, but not the first?




More information about the Python-list mailing list