Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python try block does not catch os.system exceptions

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?

like image 963
Cinder Avatar asked Sep 11 '12 15:09

Cinder


People also ask

How do you fix exception errors in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

What is OS error in Python?

OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”. Below is an example of OSError: Python.

How do I get a list of exceptions in Python?

Another way to catch all Python exceptions when it occurs during runtime is to use the raise keyword. It is a manual process wherein you can optionally pass values to the exception to clarify the reason why it was raised. if x <= 0: raise ValueError(“It is not a positive number!”)


1 Answers

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

like image 78
mgilson Avatar answered Sep 21 '22 16:09

mgilson