Subprocess.communicate 的输出类型是什么?

bad*_*093 5 python subprocess popen

我正在查看Popen.communicate()的官方文档。

p = subprocess.Popen('echo hello',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,universal_newlines=True)
r,e = p.communicate()
Run Code Online (Sandbox Code Playgroud)

我想知道在什么情况下它将返回字符串输出以及在什么情况下它将以字节为单位返回。(有例子会很棒)

在上面的例子中,r类型是字符串。

Popen.communicate(input=None, timeout=None)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate and set the returncode attribute. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.
Run Code Online (Sandbox Code Playgroud)

fla*_*kes 3

这取决于文档中使用的文本模式

如果指定了编码或错误,或者文本(也称为 universal_newlines)为 true,则文件对象 stdin、stdout 和 stderr 将使用调用中指定的编码和错误或 io.TextIOWrapper 的默认值以文本模式打开。 . 如果不使用文本模式,stdin、stdout 和 stderr 将作为二进制流打开。不执行编码或行结束转换。

对于未来类型良好的库的用例,您可以使用typing.reveal_type静态分析器,例如 mypy。这使得确定代码中的值变得非常容易。

例子,test.py

from subprocess import Popen
from typing import reveal_type

p1 = Popen("blah", text=False)
reveal_type(p1.communicate())


p2 = Popen("blah", text=True)
reveal_type(p2.communicate())
Run Code Online (Sandbox Code Playgroud)
> mypy test.py
test.py:5: note: Revealed type is "Tuple[builtins.bytes, builtins.bytes]"
test.py:9: note: Revealed type is "Tuple[builtins.str, builtins.str]"
Success: no issues found in 1 source file
Run Code Online (Sandbox Code Playgroud)

您可以在这里看到,当text=False值是字节时,当text=True值是字符串时。