Python try block does not catch os.system exceptions

前端 未结 6 1977
温柔的废话
温柔的废话 2021-01-01 10:49

I have this python code:

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

The code prints:



        
6条回答
  •  情歌与酒
    2021-01-01 10:59

    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.

提交回复
热议问题