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

mike needpassion at
Thu Jun 14 02:47:16 CEST 2007

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:
import os
import sys
import time

    fh = open("")
except IOError:
    print 'failed to open.'
    print 'Some exceptions occurred.'
    print 'well',

print 'Done'

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

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.


More information about the Python-list mailing list