[英]Pipe output of one iteration of a python for loop to another script
for循环的每个实例吐出一个二进制文件的内容,该文件应由另一脚本捕获以进行进一步处理。 例如:
script1.py
filename = glob.glob('*.txt')
for i in range(len(filename)):
with open(filename[i], 'rb') as g:
sys.stdout.write(g.read())
script2.py
from subprocess import call
script = "cat > test.fil"
call(script,shell=True)
命令:
python script1.py | python script2.py
如果执行此命令,它将等待所有迭代完成,然后再将输出传递到script2.py。 我希望分批完成。 例如,将来自一个二进制文件的数据推送到stdout后,启动script2.py。
无法从script1.py调用script2.py。 这两个脚本都需要在不同的Docker容器中运行 。 最好避免在Docker容器内安装docker。
如果sys.stdout
连接到管道,则默认情况下它将缓冲。 您必须调用sys.stdout.flush()
刷新输出:
sys.stdout.write(g.read())
sys.stdout.flush()
您的第二个脚本也可以直接读取stdin,而不是唤起shell来唤起cat来读取它。 按照您编写的方式,您正在执行3个进程(python,shell,cat)。
import shutil
import sys
with open('test.fil', 'w') as f:
shutil.copyfileobj(sys.stdin, f)
在一个不相关的音符,你并不需要使用for
在数字环路range
,当你要使用数只索引list
。 for
循环可以直接在list
元素中进行迭代:
filenames = glob.glob('*.txt')
for filename in filenames:
with open(filename, 'rb') as g:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.