您在 Python3 中使用旧版 Python2 子命令(请参阅 subprocess.getoutput docs)
部分问题是您正在使用 getoutput 将字节对象隐式转换为字符串。 0xe2 是 226,大于 ASCII 的 128 范围。
相反,您应该将 stdout 和 stderr 作为字节对象获取并在稍后的命令中进行转换。例如:
# captures the output for 1 packet.
import subprocess as sp
cmd = sp.run(["tshark", "-c", "1"], stdout=sp.PIPE, stderr=sp.PIPE)
print("STDOUT:\n", cmd.stdout, "\n\nSTDERR:\n", cmd.stderr)
给出输出
STDOUT:
b' 1 0.000000 179.118.244.35.bc.googleusercontent.com \xe2\x86\x92
192.198.128.5 TLSv1.2 105 Application Data 6c:94:cf:d8:7f:e7 \xe2\x86\x90
e0:55:3d:71:f7:29\n'
STDERR:
b"Capturing on 'Wi-Fi: en0'\n1 packets dropped from Wi-Fi: en0\n1 packets captured\n"
您现在有了用于 stdout 和 stderr 的字节对象。您可以使用任何您想要的编码(如 ASCII、UTF-8)对它们进行解码,或者在您的代码中使用它们。
您可能还想查看scapy,这是一个用于处理数据包的python库。
注意:这个例子使用了run,但是有很多Python Popen wrappers做类似的事情。