我们最近发现,如果我们通过进程替换为其输入文件提供了输入文件,我们在 python 3.x(但不是 python 2.x)中开发的脚本会阻塞,例如:
script.py <(cat *.gz)
我们已经使用 gzip 以外的命令(例如 cat)进行了测试,只是为了看看我们是否会收到类似的错误。他们都抱怨/dev/fd/63
(或/dev/fd/63.gz
)不存在。这是(简化的)相关代码:
def open_gzip_in(infile):
'''Opens a gzip file for reading, using external gzip if available'''
# Determine whether to use the gzip command line tool or not
if exeExists('gzip'):
cmd = ['gzip', '-dc', infile]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=-1,
universal_newlines=True)
if sys.version.startswith("2"):
with p.stdout:
for line in iter(p.stdout.readline, b''):
yield line
else:
with p:
for line in p.stdout:
yield line
exit_code = p.wait()
if exit_code != 0:
raise subprocess.CalledProcessError(
p.returncode, subprocess.list2cmdline(cmd), 'Ungzip failed')
else:
with io.TextIOWrapper(io.BufferedReader(gzip.open(infile))) as f:
for line in f:
yield(line)
顺便说一句,我们进行分叉只是因为命令行 gzip 比使用 gzip.open 快得多,而且我们的脚本是一个长时间运行的工作程序 - 差异是几个小时。
我们正在解决这个问题,但想了解为什么它在 python 3 中不起作用但在 python 2 中起作用。