subprocess.CalledProcessError not giving error message

I am using below code for getting output of shell command.

import subprocess
exitcode, err, out = 0, None, None
try:
    out = subprocess.check_output(cmd, shell=True, universal_newlines=True)
except subprocess.CalledProcessError as e:
    exitcode, err = e.returncode, e.output

print("x{} e{} o{}".format(exitcode, err, out))

When a valid command is being passed for cmd like echo hello, the program is running fine and giving output as (0, None, "hello\n")

But if I give a wrong kind of command I am expecting the error message should come in err, but its getting printed directly. For example if I pass ls -lrt foo in cmd the output is coming as

anirban@desktop> python mytest.py
ls: cannot access foo: No such file or directory
x2 e oNone

So I want ls: cannot access foo: No such file or directory should be coming in err. How to do that?

Upvotes: 3

Views: 3346

Answers (1)

Abhash Anand
Abhash Anand

Reputation: 326

To capture the error output, you need to pass in another argument to the subprocess.check_output() function. You need to set stderr=subprocess.STDOUT. This will channel the stderr output to e.output.

subprocess.check_output() is a wrapper over subprocess.run(). It makes our lives easier by passing in some sensible defaults. One of those is making stdout=subprocess.PIPE. This directs the standard output of the command you are running back to your program. Similarly, you can direct the standard error output to your program by passing in argument, stderr=subprocess.PIPE, this will populate e.stderr where e is the exception.

Let me know if this is not clear.

Upvotes: 4

Related Questions