子进程弹出标准输出

subprocess popen stdout

我正在学习subprocess,但我对这段代码有点困惑:

import subprocess

proc = subprocess.Popen('lspci', stdout=subprocess.PIPE)
for line in proc.stdout:
    print(line)

输出:

b'00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor DRAM Controller (rev 09)\n'
b'00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor Graphics Controller (rev 09)\n'

如您所见,输出已格式化。但是我不知道为什么最后会有b''这个字符和\n

如果我 运行 在我的终端中执行此命令,则没有这些字符。

正常输出:

00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor DRAM Controller (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor Graphics Controller (rev 09)

我怎样才能删除它们?

您可能正在使用 python3 - python 改变了某些对象 read/write 数据的方式,现在有一个真正的 bytes() 对象。要得到你想要的字符串,你只需要:

print(line.decode("utf8")) ## or some encoding; that one should print anything though

您可能还需要从输出中去除换行符 (\n);我不记得 stdout 是如何做到 buffering/reporting:

print(line.decode("utf8").strip())

我想你使用 python 3:

b是Bytes,表示是字节序列,相当于Python 2.6+

中的普通字符串

https://docs.python.org/3/reference/lexical_analysis.html#literals

b'' 是 Python 中 bytes 个对象的文本表示 3.

要按原样打印字节,请使用二进制流 -- sys.stdout.buffer:

#!/usr/bin/env python3
import sys
from subprocess import Popen, PIPE

with Popen('lspci', stdout=PIPE, bufsize=1) as process:
    for line in process.stdout: # b'\n'-terminated lines
        sys.stdout.buffer.write(line)
        # do something with line here..

要将输出作为文本(Unicode 字符串),您可以使用 universal_newlines=True 参数:

#!/usr/bin/env python3
from subprocess import Popen, PIPE

with Popen('lspci', stdout=PIPE, bufsize=1, universal_newlines=True) as process:
    for line in process.stdout: # b'\n', b'\r\n', b'\r' are recognized as newline
        print(line, end='')
        # do something with line here..

locale.getpreferredencoding(False)字符编码用于解码输出。

如果子进程使用不同的编码,那么您可以使用 io.TextIOWrapper():

明确指定它
#!/usr/bin/env python3
import io
from subprocess import Popen, PIPE

with Popen('lspci', stdout=PIPE, bufsize=1) as process:
    for line in io.TextIOWrapper(process.stdout, encoding='utf-8'):
        print(line, end='')
        # do something with line here..

有关 Python 2 代码和可能问题的链接,请参阅 Python: read streaming input from subprocess.communicate()