Python try block does not catch os.system exceptions

前端 未结 6 1980
温柔的废话
温柔的废话 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

    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 os
    try:
      os_cmd = 'wrongcommand'
      if os.system(os_cmd) != 0:
          raise Exception('wrongcommand does not exist')
    except:
      print("command does not work")
    
    

提交回复
热议问题