【问题标题】:How to decompress BZ2 directly into Popen stdin in Python 2.7?如何在 Python 2.7 中将 BZ2 直接解压成 Popen 标准输入?
【发布时间】:2015-03-20 10:38:12
【问题描述】:

场景:PCAP 用BZIP2 压缩的文件,我想用tcpdump 解析并在 Python 2.7 中逐行列出结果。以下是我的想法:

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 参数需要一个实际的文件句柄并抛出此异常:

AttributeError: 'bz2.BZ2File' 对象没有属性 'fileno'

我可以轻松地将其设为两步过程,但我想避免使用中间临时文件。

想法或建议?

【问题讨论】:

  • 除了 bzip2 问题之外,Popen(('tcpdump', '-l -n -s 0 -r -')) 与 tcpdump "-l -n -s 0 -r -" 相同,在命令行上也不起作用;你不能在一个大的单一参数中传递所有不相关的选项。
  • @CharlesDuffy 谢谢——修复!

标签: python python-2.7 popen bzip2


【解决方案1】:

使用两个不同的 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''):
    ...

【讨论】:

    【解决方案2】:

    为避免bunzip2 依赖,您可以手动抽取输入:

    import subprocess
    import threading
    from contextlib import closing
    
    p = subprocess.Popen(['tcpdump', '-lnr', '-s', '0', '-'],
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=-1)
    threading.Thread(target=pump, args=[filename, p.stdin]).start()
    with closing(p.stdout):
         for line in iter(p.stdout.readline, b''):
             print line,
    p.wait()
    

    pump() 在哪里:

    from shutil import copyfileobj
    
    def pump(filename, pipe):
        """Decompress *filename* and write it to *pipe*."""
        with closing(pipe), bz2.BZ2File(filename) as input_file:
             copyfileobj(input_file, pipe)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 2018-12-13
      • 2018-08-14
      相关资源
      最近更新 更多