[Python] - subprocess issue

So I have this basic script, see below

import subprocess
import shlex

command = "gcloud projects list"

subprocess.check_output(shlex.split(command))
subprocess.check_call(shlex.split(command))

The subprocess.check_call(shlex.split(command)) actually return what I expect. It returns the result of gcloud projects list. However subprocess.check_output doesn't, in fact it returns nothing.

Can explain this?

My understanding is the operation of the two are different:

Documentation -

Try getting get rid of the shlex,

subprocess.check_output( [ "command" "parameter_1" ])

It is also possible that the command that you are running is sending the output to stderr instead of stdout

Try this instead:-

subprocess.check_output(shlex.split(command), stderr=subprocess.STDOUT)

That's not going to work. I need the shlex and even if I didn't have it, it still wouldn't work.

That doesn't work etiher. Also the exact same command works with subprocess.check_call. What's weird is the subprocess.check_output works in the python shell but not from the python script.

To see the output from program, you have to print the output. I believe stdout is used internally for this function:-

print subprocess.check_output(shlex.split(command))
1 Like

That does work. Why does it work from the python shell without print?

Also I looked at 17.1. subprocess � Subprocess management � Python 2.7.16 documentation and it doesn't mention anything about having to do a print.