Python try block does not catch os.system exceptions

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

import subprocess
try:
    subprocess.run(['wrongcommand'], check = True)
except subprocess.CalledProcessError:
    print ('wrongcommand does not exist')

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


Because os.system() indicates a failure through the exit code of the method

  • return value == 0 -> everything ok
  • return value != 0 -> some error

The exit code of the called command is directly passed back to Python.

There is documentation telling you that os.system() would raise an exeption in case of a failure. os.system() just calls the underlaying system() call of the OS and returns its return value.

Please read the os.system() documentation carefully.