简体   繁体   中英

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?

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(), eg:

>>> 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.

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'

The subprocess module provides a method check_output() that runs 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 code above will print hello world

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

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

Using text=True in Python 3.7+

In newer versions of Python, you can simply use text=True to get a string return value:

>>> import subprocess
>>> subprocess.check_output(["echo", "hello"], text=True)
'hello\n'

Here is what the docs say :

If encoding or errors are specified, or text is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the io.TextIOWrapper default. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM