python - 使用进程替换作为 Python 的输入文件两次

标签 python linux process-substitution

考虑以下 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 - 使用进程替换作为 Python 的输入文件两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22777522/

相关文章:

python - conda 安装 python=3.6 UnsatisfiableError

python - 名称实体识别NLTK回顾

python - 从自动化器运行 python 脚本

arrays - 每个数组条目的过程替换,没有评估

python - 如何修复 conda 中的包解析警告?

linux - 尾部 : cannot open ‘+2’ for reading: No such file or directory

c - 在线程内实现计时器的最佳方法是什么?

python - 在 Ubuntu 上通过 pyODBC 连接到 Microsoft SQL Server

Bash 在循环中设置一个全局变量并保留它的值——或者进程替换为假人

linux - Bash 脚本进程替换语法错误 : "(" unexpected