【问题标题】:Python piping to `gzip.open` filehandlePython管道到`gzip.open`文件句柄
【发布时间】:2016-04-04 01:58:26
【问题描述】:

以下代码 sn -p 打开一个 gzip 文件句柄并向其中写入一行,然后以附加模式再次打开它并将子进程的标准输出重定向到 gzip 文件句柄。

import gzip
import subprocess

with gzip.open("./file.txt.gz", "w") as fh:
    fh.write("this is the first line\n")

with gzip.open("./file.txt.gz", "a") as fh:
    subprocess.call("echo this is the second line", shell=True, stdout=fh)

当我尝试解压缩文件以查看我写入的内容时,我收到以下错误

$ gunzip file.txt.gz
gzip: file.txt.gz: decompression OK, trailing garbage ignored

解压后的内容只包含第一行

$ cat file.txt
this is the first line

当我使用相同的文件句柄来写入一行并作为进程的输出时,我得到了一个 gunzip 甚至无法识别的文件。

import gzip
import subprocess

with gzip.open("./file.txt.gz", "w") as fh:
    fh.write("this is the first line\n")
    subprocess.call("echo this is the second line", shell=True, stdout=fh)

例如,生成一个不能为gunzip'd 的文件。

$ gunzip file.txt.gz

gzip: file.txt.gz: not in gzip format

有没有办法将 gzip 风格的伪文件句柄传递给通过 subprocess 运行的进程,或者真的没有其他方法可以写入非压缩文件然后返回并压缩它?

【问题讨论】:

    标签: python gzip


    【解决方案1】:

    如果你搜索 StackOverflow,你会发现这个问题偶尔会出现,但答案并不总是很容易实现。它们的要点似乎是subprocess.call() 不能传递伪文件句柄——它必须是真实的。标准的解决方法似乎是使用subprocess.Popen()。

    但是,我想出一个简单的折衷方案:

    import gzip
    import subprocess
    
    with gzip.open("file.txt.gz", "wt") as handle:
        handle.write("this is the first line\n")
    
    completed = subprocess.run("echo 'this is the second line'", shell=True, stdout=subprocess.PIPE, universal_newlines=True)
    
    with gzip.open("file.txt.gz", "at") as handle:
        handle.write(completed.stdout)
    

    这个想法是延迟附加压缩数据,直到子进程完成:

    > gzcat file.txt.gz
    this is the first line
    this is the second line
    > 
    

    subprocess.run() 函数是在 Python 3.5 中添加的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 2018-04-26
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多