我可以在 Python 中将打开的 gzip 文件与 Popen 一起使用吗? [英] Can I use an opened gzip file with Popen in Python?

查看:48
本文介绍了我可以在 Python 中将打开的 gzip 文件与 Popen 一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从标准输入读取的小命令行工具.在命令行上,我会运行...

I have a little command line tool that reads from stdin. On the command line I would run either...

./foo < bar

或...

cat bar | ./foo

使用 gzip 压缩文件我可以运行

With a gziped file I can run

zcat bar.gz | ./foo

在 Python 中我可以做...

in Python I can do ...

Popen(["./foo", ], stdin=open('bar'), stdout=PIPE, stderr=PIPE)

但我做不到

import gzip
Popen(["./foo", ], stdin=gzip.open('bar'), stdout=PIPE, stderr=PIPE)

我不得不跑步

p0 = Popen(["zcat", "bar"], stdout=PIPE, stderr=PIPE)
Popen(["./foo", ], stdin=p0.stdout, stdout=PIPE, stderr=PIPE)

我做错了吗?为什么我不能使用 gzip.open('bar') 作为 Popen 的标准输入参数?

Am I doing something wrong? Why can't I use gzip.open('bar') as an stdin arg to Popen?

推荐答案

因为子进程的 'stdin' 和 'stdout' 需要文件描述符(它是一个数字),这是一个操作系统资源.这被以下事实掩盖:如果您传递一个对象,子流程模块会检查该对象是否具有fileno"属性,如果有,它将使用它.

Because the 'stdin' and 'stdout' of the subprocess takes file descriptor (which is a number), which is an operating system resource. This is masked by the fact that if you pass an object, the subprocess module checks whether the object has a 'fileno' attribute and if it has, it will use it.

'gzip' 对象不是操作系统提供的.打开的文件是,套接字是,管道是.Gzip 对象是一个提供 read() 和 write() 方法但没有 fileno 属性的对象.

The 'gzip' object is not something an operating system provides. An open file is, a socket is, a pipe is. Gzip object is an object that provides read() and write() methods but no fileno attribute.

您可以查看子进程的communication() 方法,但您可能想使用它.

You can look at the communicate() method of subprocess though, you might want to use it.

这篇关于我可以在 Python 中将打开的 gzip 文件与 Popen 一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆