Catching Python exceptions from C++ ...

Skip Montanaro skip at
Wed Jul 4 11:42:18 CEST 2001

    Sandy> 2. Can I perhaps set stdin, stdout, stderr to my own FILE handles
    Sandy>    and at least dump the output/trace info to something I can
    Sandy>    read later? If so, how?

You could wrap the Python code you call in a try/except, then catch and save
the exception:

    import traceback, sys
        ... original code ...
        traceback.print_tb(sys.exc_info()[2], 0, open("/tmp/traceback", "w"))

The raise call is there so the return value of PyRun_SimpleFileExFlags is
the same.  It's not strictly necessary.

Skip Montanaro (skip at

More information about the Python-list mailing list