如何将子流程的每个输出追加到列表中?

2024-03-28 21:13:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获取p5的输出,它们是mac地址,我想把它们存储到一个列表中。你知道吗

我知道mac地址是以字节类型打印的,但我无法按我想要的类型打印。你知道吗

p3 = subprocess.Popen(["iw", "dev", displayInt, "station", "dump"], stdout=subprocess.PIPE)

p4 = subprocess.Popen(["grep", "Station"], stdin=p3.stdout,  stdout=subprocess.PIPE)

p5 = subprocess.Popen(["cut", "-f", "2", "-s", "-d", " "], stdin=p4.stdout, stdout=subprocess.PIPE)

for line in iter(p5.stdout.readline,''):
    maclist.append(line.rstrip('\n'))
print(maclist)

我希望输出如下:

[a1:b2:c3:d4:e5:f6 , a1:b2:c3:d4:e5:f6]

我得到以下错误:

TypeError: a bytes-like object is required, not 'str'

Tags: 类型mac地址a1stdinstdoutlineb2
1条回答
网友
1楼 · 发布于 2024-03-28 21:13:04

你好像在用Python3。在python3中,stdout是字节流。如果要将其转换为字符串,请将encoding='utf8'参数添加到Popen()调用中,例如:

p5 = subprocess.Popen(
    ["cut", "-f", "2", "-s", "-d", " "],
    encoding="utf8",
    stdin=p4.stdout,
    stdout=subprocess.PIPE)

对于其他调用,可能必须包含encoding参数。同时,代替:

for line in iter(p5.stdout.readline,''):

您可能想试试这个简短易懂的方法:

for line in p5.stdout:

相关问题 更多 >