yes ok
yes ok

Reputation: 3

How can I check if a command was succesful or not?

So, I'm trying to check if the command was successful or not when doing subprocess command.

I'm really bad at explaining but just look at my example:

Here's my code

output = subprocess.getoutput("sdf")
print(output)

I want to check if the output is:

'sdf' is not recognized as an internal or external command,
operable program or batch file.

I tried this code:

error_temp = fr"'sdf' is not recognized as an internal or external command, operable program or batch file."
if output == error_temp:
   print("'sdf' was not recognized by this system, please register this command and try again later.")
else:
   print(output)

But it's not really working, I think it's got to do with a skip line in the output...

Any help is appreciated, thanks.

EDIT:

I fixed this problem thanks to @Cristian

Here's my updated code:

status = subprocess.getstatusoutput("sdf")
print(status[0])

Upvotes: 0

Views: 2594

Answers (2)

Booboo
Booboo

Reputation: 44013

I just want to show an alternative to getstatusoutput, an older method that always launches a shell to execute your program, which may be inefficient if you do not need the facilities that a shell provides (such as wildcard expansion).

The following uses subprocess.run (which can also use a shell to execute your program if you specify shell=True). The first example does not capture the output from the executed program and the second example does. The program being run is a small Python program, test.py, executed with the command python test.py

test.py

print('It works.\n')

Example 1 -- Do not capture output

import subprocess


completed_process = subprocess.run(['python', 'test.py'])
print(completed_process.returncode)

Prints:

It works.
0

Example 2 -- Capture output

import subprocess


completed_process = subprocess.run(['python', 'test.py'], capture_output=True, text=True)
print(completed_process.returncode)
print(completed_process.stdout)

Prints:

0
It works.

Upvotes: 1

Cristian
Cristian

Reputation: 129

You can use the getstatusoutput function from the same package. It returns a tuple with the exit code and the message. If the exit code is 0, it is considered as a successful completion. Other codes indicate an abnormal completion.

Upvotes: 1

Related Questions