Can I have subprocess.call write the output of a call to a string?

I want to do subprocess.call and get the call output to a string. Can I do this directly or do I need to transfer it to a file and then read from it?

In other words, can I somehow redirect stdout and stderr to a string?

+7
source share
4 answers

No, you cannot directly read the output of subprocess.call () into a string.

To read the output of a command into a string, you need to use subprocess.Popen (), for example:

>>> cmd = subprocess.Popen('ls', stdout=subprocess.PIPE) >>> cmd_out, cmd_err = cmd.communicate() 

cmd_out will have a line with the output of the command.

+8
source

The subprocess module provides the check_output() method, which executes the provided command with arguments (if any) and returns its output as a byte string.

 output = subprocess.check_output(["echo", "hello world"]) print output 

The above code will print hello world

See docs: https://docs.python.org/2/library/subprocess.html#subprocess.check_output

+5
source

This is an extension of the mantazer answer in python3. You can still use subprocess.check_output command in python3:

 >>> subprocess.check_output(["echo", "hello world"]) b'hello world\n' 

however now it gives us a byte string. To get the real python string, we need to use decoding:

 >>> subprocess.check_output(["echo", "hello world"]).decode(sys.stdout.encoding) 'hello world\n' 

Using sys.stdout.encoding as the encoding, and not just the default UTF-8 should do this job for any OS (at least theoretically).

The final new line (and any other extra spaces) can be easily removed with .strip() , so the last command:

 >>> subprocess.check_output(["echo", "hello world"] ).decode(sys.stdout.encoding).strip() 'hello world' 
+4
source

subprocess.call() takes the same arguments as subprocess.Popen() , which includes the arguments stdout and stderr . See the docs for more details.

+2
source

All Articles