将python for循环的一次迭代输出到另一个脚本

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 

如果我执行这个命令,它将等待所有迭代完成,然后将输出pipe道输出到script2.py。 我希望这是分批进行的。 例如,一旦将一个二进制文件的数据推送到标准输出,启动script2.py。

script2.py不能从script1.py中调用。 这两个脚本需要在不同的docker容器中运行 。 最好避免在Docker容器中安装docker。

如果sys.stdout连接到一个pipe道,默认情况下它缓冲。 您必须调用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) 

在不相关的注释中,当您打算只使用数字来索引list时,您不需要在数字range使用for循环。 for循环可以直接在list元素中迭代:

 filenames = glob.glob('*.txt') for filename in filenames: with open(filename, 'rb') as g: ...