python - 如何在Python 2.7中将BZ2直接解压到Popen stdin中?

标签 python python-2.7 popen bzip2

场景:使用 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()

问题是 Popenstdin 参数需要一个实际的文件句柄并抛出此异常:

属性错误:“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/

相关文章:

python - pandas stack/unstack 使用交换级别 reshape df

Python-存在多个同名元素属性时如何编辑特定的XML元素内容?

python - Popen 包含需要对所有输出说是的命令

python subprocess - 如何检查 PIPE 中是否没有任何新数据?

Python FFMPEG AttributeError : 'Popen' object has no attribute 'proc'

python - 获取对特定推文的回复计数

javascript - 使用 JS/CSS 缩小工具作为 python distutils 命令?

python - 如何滚动弹性查询结果,python

python - 如何按特定字符的计数对字符串列表进行排序?

visual-c++ - 嵌入式 Python 应用程序中的运行时错误 R6034