Python try block does not catch os.system exceptions Python try block does not catch os.system exceptions python python

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 subprocesstry:    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.


Although subprocess might be your best friend. os.system is still useful in somewhere, especially to the programmer play C/C++ mode.

Hence, the code will be below.

import ostry:  os_cmd = 'wrongcommand'  if os.system(os_cmd) != 0:      raise Exception('wrongcommand does not exist')except:  print("command does not work")