Capturing errors raised by other scripts ?

Lie Ryan lie.1296 at
Sat Feb 20 09:04:22 CET 2010

On 02/20/10 14:39, northof40 wrote:
> On Feb 20, 4:13 pm, MRAB <pyt... at> wrote:
>> northof40 wrote:
>>> I'm using the subroutine module to run run python script from
>>> (this is on windows fwiw).
>>> is not my script and it may raise arbitary errors before exiting.
>>> How can I determine what's happened before exited ?
>>> To simulate this I've got this script (which is meant to simulate
>>> class customError(Exception):
>>>    def __init__(self, value):
>>>            self.value = value
>>>    def __str__(self):
>>>            return repr(self.value)
>>> try:
>>>    raise customError(2*2)
>>> except customError as e:
>>>    print 'Custom exception occurred, value:', e.value
>>> I then run my like this :
>>>>>> fdOut, fOut = tempfile.mkstemp(suffix='.txt', prefix='AOut-')
>>>>>> fdErr, fErr = tempfile.mkstemp(suffix='.txt', prefix='AErr-')
>>>>>> try:
>>> ...     pathtojob="python.exe"
>>> ...     p = subprocess.Popen(pathtojob, stderr=fdErr, stdout=fdOut)
>>> ... except:
>>> ...     print "bad stuff happened"
>>> ...
>>> When I do this I the exception handler is not fired and the text
>>> "Custom exception occurred, value: 4" ends up in the stdout file.

>>> I'd really like it to end up in stderr because then I could say
>>> "anything in stderr ? then ignore the output and flag an error".

Not really; not all that is written to stderr signifies errors per se.
Warning and Debugging info are often written to stderr as well.

> Thanks for your reply. I take your point about print - perhaps I
> hadn't really thought that through. Unfortunately I don't have control
> of the real script that's being run so if the programmer of that
> script has used print there's nothing I can do about it.

Tracebacks is almost always written to stderr, not stdout; unless the
programmer explicitly redirect the traceback into stdout.

> Perhaps I could modify the question. If terminates due an
> unhandled exception is there anyway for to know that's happened
> (without's cooperation ?).

A well-behaved program will exit with status code 0; if and only if it
exited cleanly. I believe a python program that exited due to unhandled
exception always return non-zero status code.

However, if the program handled an error and called exit(0) explicitly
or the execution of the program falls to the end of the module; there is
no way to distinguish it from regular clean exit.

More information about the Python-list mailing list