开发者

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?

开发者_JAVA百科

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


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.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜