【发布时间】: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 运行的进程,或者真的没有其他方法可以写入非压缩文件然后返回并压缩它?
【问题讨论】: