如何将 python 程序的标准输出提供给 Popen 标准输入?

How to feed standard output of a python program into Popen standard input?

目前,我有解压缩文件然后使用 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?

我可以通过调用 Popen.wait() 写入 outfile.gz

来实现此功能