How can I capture all exceptions especially when os.system() fail? Thanks

M

mike

Hi Guys,

Following piece of code can capture IOError when the file doesn't
exist, also, other unknown exceptions can be captured when I press
Ctrl-C while the program is sleeping(time.sleep). Now the question is:
when I run the non-exist command, the exception cannot be captured.

Here is the code:
===================================
#!/usr/bin/python
import os
import sys
import time

try:
fh = open("tt.py")
time.sleep(10)
#os.system("wrong_command_test")
except IOError:
print 'failed to open.'
sys.exit(0)
except:
print 'Some exceptions occurred.'
else:
print 'well',

print 'Done'

===================================
when the tt.py doesn't exist, the script printed:
failed to open.
when the tt.py exists, the script printed:
well done
when I press Ctrl-C while the program is sleeping, the script printed:
Some exceptions occurred.
Done

So far so good, then I changed the code to run a non-exist command
"wrong_command_test"(commented the open and sleep lines), then the
script printed:
sh: wrong_command_test: command not found
well Done


Any opinions would be appreciated.

Mike
 
G

Gabriel Genellina

Following piece of code can capture IOError when the file doesn't
exist, also, other unknown exceptions can be captured when I press
Ctrl-C while the program is sleeping(time.sleep). Now the question is:
when I run the non-exist command, the exception cannot be captured.
So far so good, then I changed the code to run a non-exist command
"wrong_command_test"(commented the open and sleep lines), then the
script printed:
sh: wrong_command_test: command not found
well Done

That's because it is not an exception, it is an error message coming from
your shell, not from Python.
You can extract the exit status from what os.system returns (see the
details on the docs for os.system); in particular, usually "command not
found" is error 127
This is a list of more-or-less standard exit codes:
http://www.faqs.org/docs/abs/HTML/exitcodes.html
 
M

Michael Hoffman

Gabriel said:
That's because it is not an exception, it is an error message coming
from your shell, not from Python.

Of course if you use subprocess.check_call() instead of os.system(), it
will become an exception (CalledProcessError).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top