场景:使用 BZIP2
压缩的 PCAP
文件,我想在 Python 2.7 中使用 tcpdump
解析该文件并逐行列出结果。这是我突然想到的:
def tcpdump(filename):
import subprocess
import bz2
p = subprocess.Popen(
('tcpdump', '-lnr', '-s', '0', '-'),
stdin=bz2.BZ2File(filename),
stdout=subprocess.PIPE)
try:
for row in p.stdout:
yield row.rstrip()
except KeyboardInterrupt:
p.terminate()
问题是 Popen
的 stdin
参数需要一个实际的文件句柄并抛出此异常:
属性错误:“bz2.BZ2File”对象没有属性“fileno”
我可以轻松地将此过程分为两步,但我想避免使用中间临时文件。
想法或建议?
最佳答案
使用两个不同的 Popen 对象:
p1 = subprocess.Popen(['bunzip2', '-c', filename],
stdout=subprocess.PIPE)
p2 = subprocess.Popen(['tcpdump', '-lnr', '-s', '0', '-'],
stdin=p1.stdout,
stdout=subprocess.PIPE)
p1.stdout.close()
for row in iter(p2.stdout.readline, b''):
...
关于python - 如何在Python 2.7中将BZ2直接解压到Popen stdin中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075193/