在对row1 col2运行子流程之前,我需要读取一个文件并将row1 col1附加到文件中,子流程的结果将附加在初始附加行下面。本质上,在继续下一行并再次启动之前,对输出文件进行附加、处理和附加
到目前为止我有什么
import subprocess as sp
with open(fin) as f:
out = open(fout, 'a')
while (lin := f.readline().rstrip().split()):
out.write(lin[0] + 'n')
cmd = ['cmd', lin[1]]
sp.run(' '.join(cmd), shell=True, stdout=out, stderr=sp.STDOUT)
我在输出中得到了结果,但子流程运行结果是首先写在我想在每个子流程运行的结果之前附加的所有行之前的。所以我想要的是:
appended col[0] of row1
result of subprocess run on col[1] of row1
appended col[0] of row2
result of subprocess run on col[1] of row2
我得到了这个:
result of subprocess run on col[1] of row1
result of subprocess run on col[1] of row2
appended col[0] of row1
appended col[0] of row2
任何帮助都将不胜感激。
在out.write()
调用后添加out.flush()
。Python缓冲区中的东西不会被刷新,因为它不知道你在调用外部进程