Capturing errors raised by other scripts ?

MRAB python at mrabarnett.plus.com
Fri Feb 19 22:13:10 EST 2010


northof40 wrote:
> I'm using the subroutine module to run run python script A.py from
> B.py (this is on windows fwiw).
> 
> A.py is not my script and it may raise arbitary errors before exiting.
> How can I determine what's happened before A.py exited ?
> 
> To simulate this I've got this script (which is meant to simulate
> A.py):
> 
> 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 A.py like this :
> 
>>>> fdOut, fOut = tempfile.mkstemp(suffix='.txt', prefix='AOut-')
>>>> fdErr, fErr = tempfile.mkstemp(suffix='.txt', prefix='AErr-')
>>>> try:
> ...     pathtojob="python.exe A.py"
> ...     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".
> 
> I don't want to have to parse the stdout for error like messages and I
> can't make changes to A.py.
> 
> I'm sure there's a better way to do this - can anyone offer some
> advice ?
> 
> thanks
> 
A.py is printing the error message.

The 'print' statement prints to stdout unless you direct it elsewhere
with '>>', for example:

     print >> my_file, 'message'

If you don't want error messages to go to stdout, then don't print them
to stdout, it's as simple as that!



More information about the Python-list mailing list