AnojiRox AnojiRox - 3 months ago 71
Python Question

Python try block does not catch os.system exceptions

I have this python code:

import os
try:
os.system('wrongcommand')
except:
print("command does not work")


The code prints:

wrongcommand: command not found


Instead of
command does not work
. Does anyone know why it's not printing my error message?

Answer

If you want to have an exception thrown when the command doesn't exist, you should use subprocess:

 import subprocess
 try:
     subprocess.call(['wrongcommand'])
 except OSError:
     print ('wrongcommand does not exist')

Come to think of it, you should probably use subprocess instead of os.system anyway ...