Catching external program exceptions

Marty martyb1 at earthlink.net
Tue Jan 1 17:57:44 EST 2008


I need to catch exceptions thrown by programs started by the os.system function, 
as indicated by a non-zero return code (e.g. the mount utility).  For example, 
if I get the following results in a bash shell:

$mount test
mount: can't find /home/marty/test in /etc/fstab or /etc/mtab

then I want to catch the same exception from the corresponding os.system() call, 
i.e. "os.system('mount test')", but it doesn't work as expected:


 >>> import os, sys
 >>> try: os.system('mount test')
... except: print 'error'
...
mount: can't find /home/marty/test in /etc/fstab or /etc/mtab
256
 >>>

I get the same results with popon, popen2, popen3, etc.  Apparently these also 
work only when the program does not generate an exception.  Is there any way to 
catch the return code. or if not, a workaround?



More information about the Python-list mailing list