48

I have this python code:

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

The code prints:

wrongcommand: command not found

Instead of command does not work. Does anyone know why it's not printing my error message?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Cinder
  • 1,599
  • 2
  • 13
  • 23

6 Answers6

66

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

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • My command is for running a .jar file. When I run the correct command with square braces the above snippet still showing the exception. When I run the wrong command without square braces the above snippet not showing the exception. How to handle this? – Shiva Krishna Chippa Aug 20 '19 at 08:44
  • What does your command look like? I suspect that you want something like: `subprocess.call(["java", "-jar", "yourjar.jar"])` – mgilson Aug 22 '19 at 03:13
  • `sikuli_jar = "C:\\sikulix.jar" sikuli_script = "C:\\Sikuli.sikuli" try: command = "java -jar {} -r {}".format(sikuli_jar, sikuli_script) subprocess.call([command]) except OSError: raise ("\"{}\" \"{}\" one of these is missing.".format(sikuli_jar, sikuli_script))` With the above I was facing problem. – Shiva Krishna Chippa Aug 23 '19 at 05:49
  • 2
    But fixed with below code. `try: command = "java -jar {} -r {}".format(sikuli_jar, sikuli_script) subprocess.check_call(command) except (OSError, subprocess.SubprocessError, subprocess.CalledProcessError): raise ("\"{}\" \"{}\" one of these is missing.".format(sikuli_jar, sikuli_script))` – Shiva Krishna Chippa Aug 23 '19 at 05:54
  • @ShivakrishnaChippa, can you add your answer as an `EDIT:` to your question! It would be easier to read instead of what's in the comment! – Anu Aug 09 '20 at 05:49
  • With SSH keys in place, when invoked with `subprocess.call()`, `rsync` asks for a password, but does not ask when invoked with `os.system()`. Did I miss something? – Eric Nelson Jun 03 '21 at 02:58
34

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.

Islam
  • 3,654
  • 3
  • 30
  • 40
18

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")

Shouton Eulle
  • 181
  • 1
  • 5
5

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.

Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130
1

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

gefei
  • 18,922
  • 9
  • 50
  • 67
  • thanks, but how do you catch it in python? is it even possible? – Cinder Sep 11 '12 at 15:55
  • 1
    Yes, but not using `os.system()`. This is one reason why you should use the `subprocess` module, as outlined in @mgilson's answer. – Dr. Jan-Philip Gehrcke Sep 11 '12 at 16:02
  • More specifically, `wrongcommand: command not found` is the output of the *shell* that `os.system` is using to invoke the command. (a different shell with a different `PATH` might find the command). – mgilson Sep 11 '12 at 16:07
1

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()