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?
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 ...
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.
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.
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With