【问题标题】:How to feed standard output of a python program into Popen standard input?如何将 python 程序的标准输出输入 Popen 标准输入?
【发布时间】:2019-11-23 21:55:57
【问题描述】:

目前,我有代码可以解压缩一个文件,然后使用 Popen 将其压缩到另一个文件中

with open('./file.gz', 'rb') as in_file:
    g_unzip_process = Popen(['gunzip', '-c'], stdin=in_file, stdout=PIPE)

with open('./outfile.gz', 'wb+') as out_file:
    Popen(['gzip'], stdin=g_unzip_process.stdout, stdout=out_file)

现在,我正在尝试在两者之间插入一些东西。

应该是这样的:

with open('./file.gz', 'rb') as in_file:
    g_unzip_process = Popen(['gunzip', '-c'], stdin=in_file, stdout=PIPE)

transform_process = Popen(['python', 'transform.py'], stdin=g_unzip_process.stdout, stdout=PIPE)

with open('./outfile.gz', 'wb+') as out_file:
    Popen(['gzip'], stdin=transform_process.stdout, stdout=out_file)

我的 transform.py 代码如下所示

for line in sys.stdin:
    sys.stdout.write(line)
sys.stdin.close()
sys.stdout.close()

运行后,为什么我的outfile.gz文件是空的? 我还尝试通过运行阅读每一行:

for line in transform_process.stdout:
    print(line)

我怎样才能让这些行写入 outfile.gz 中?

【问题讨论】:

    标签: python io pipe gzip popen


    【解决方案1】:

    我可以通过调用 Popen.wait() 写入 outfile.gz 来完成这项工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 2013-09-18
      • 2018-12-13
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多