使用进程替换作为Python的输入文件两次
作者:互联网
考虑以下python脚本
#test.py
import sys
inputfile=sys.argv[1]
with open(inputfile,'r') as f:
for line in f.readlines():
print line
with open(inputfile,'r') as f:
for line in f.readlines():
print line
现在我想在替换进程上运行test.py,例如,
python test.py <( cat file | head -10)
似乎第二个f.readlines返回空.为什么这样做,有没有办法做到这一点,而无需指定两个输入文件?
解决方法:
>为什么这样.
>进程替换通过创建命名管道来工作.所以在第一个打开/读取循环中消耗的所有数据.
>有没有办法做到这一点,而无需指定两个输入文件.
>如何在使用之前缓冲数据.
这是一个示例代码
import sys
import StringIO
inputfile=sys.argv[1]
buffer = StringIO.StringIO()
# buffering
with open(inputfile, 'r') as f:
buffer.write(f.read())
# use it
buffer.seek(0)
for line in buffer:
print line
# use it again
buffer.seek(0)
for line in buffer:
print line
标签:python,linux,process-substitution 来源: https://codeday.me/bug/20190830/1771681.html