Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 377
alexgolec Avatar asked May 05 '11 18:05

alexgolec


People also ask

How do I get the output of a subprocess call?

communicate() #Another way to get output #output = subprocess. Popen(args,stdout = subprocess. PIPE). stdout ber = raw_input("search complete, display results?") print output #... and on to the selection process ...

How do you read subprocess Popen output?

popen. To run a process and read all of its output, set the stdout value to PIPE and call communicate(). The above script will wait for the process to complete and then it will display the output.

What is difference between subprocess Popen and call?

Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.


2 Answers

This is an extension of mantazer's answer to python3. You can still use the 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 a real python string we need to use decode:

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

Using sys.stdout.encoding as the encoding rather than just the default UTF-8 should make this work on any OS (at least in theory).

The trailing newline (and any other extra whitespace) can be easily removed using .strip(), so the final command is:

>>> subprocess.check_output(["echo", "hello world"]
                            ).decode(sys.stdout.encoding).strip()
'hello world'
like image 72
dshepherd Avatar answered Oct 18 '22 02:10

dshepherd


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

In order to read the output of a command into a string, you need to use subprocess.Popen(), e.g.:

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

cmd_out will have the string with the output of the command.

like image 30
aeter Avatar answered Oct 18 '22 04:10

aeter