Python try block does not catch os.system exceptions

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

    0 讨论(0)
  • 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")
    
    
    0 讨论(0)
  • 2021-01-01 11:00

    wrongcommand: command not found is the output of the shell os.system is using to invoke the command. os.system did not throw an exception

    EDIT: edited by copy-and-pasting part of mgilson's comment

    0 讨论(0)
  • 2021-01-01 11:04

    There is one more easiest ways is:

    import os
    
    def dat():
            if os.system('date') == 0:
                print("Command successfully executed")
            else:
                print("Command failed to execute")
    
    dat()
    
    0 讨论(0)
  • 2021-01-01 11:06

    There are two problems in your code snippet. First of all, never just do try: ... except:, always be specific about which exception you want to handle. Otherwise, your program simply swallows any kind of error, also those that you do not expect. In most cases, this will lead to unexpected behavior at some other point during runtime.

    Furthermore, os.system() calls should most of the time be replaced by their counterparts from the subprocess module.

    To see what goes wrong, leave out the try/except block and actually look at the traceback/exception. As others have pointed out, you will notice that there is no exception in your case which is why your custom string is not printed.

    Bottom line: think about which specific exceptions can occur in your code block. Think hard about which of them you expect to happen for certain reasons and handle those appropriately. Do not handle those that you do not expect.

    0 讨论(0)
  • 2021-01-01 11:08

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

    0 讨论(0)
提交回复
热议问题