我正在尝试获取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'
答案 0 :(得分:1)
似乎您正在使用Python3。在Python 3中,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: