python subprocess.call()未在循环中执行

python subprocess.call()未在循环中执行,python,python-2.7,python-3.x,subprocess,Python,Python 2.7,Python 3.x,Subprocess,我有下面一段代码,它使用gnuplot生成绘图: import sys, glob, subprocess, os, time for file in glob.glob('comb_*.out'): fNameParts = file[5:].split('.')[0].split('-') gPlotCmd = [] gPlotCmd = 'unset border; set xl "rotation period #"; set yl "T [K]"\n'

我有下面一段代码,它使用gnuplot生成绘图:

import sys, glob, subprocess, os, time
for file in glob.glob('comb_*.out'):
    fNameParts = file[5:].split('.')[0].split('-')
    gPlotCmd = []
    gPlotCmd = 'unset border; set xl "rotation period #"; set yl "T [K]"\n'
    gPlotCmd += 'set key above\n'
    gPlotCmd += 'set grid xtics ytics\n'
    gPlotCmd += 'set term post eps enh color solid\n'
    gPlotCmd += 'set xrange [20:876]\n'
    gPlotCmd += 'set output "fig_TestRelax-' + fNameParts[1] + '-' + fNameParts[2] + '-' + fNameParts[3]  + '-' + fNameParts[4] + '.eps"\n'
    conf = fNameParts[1] + '-' + fNameParts[2] + '-' + fNameParts[3]
    gPlotCmd += 'plot "' + file + '" using ($1/36000):($9-$3) w l lw 5 title "OP3-OP1 ' + conf + '", "' + file + '" using ($1/36000):($6-$3) w l lw 3 title "OP2-OP1 ' + conf + '", "' + file + '" using ($1/36000):($9-$6) w l lw 1 title "OP3-OP2 ' + conf + '"'
    fw = open('temp.plt','w+')
    fw.writelines(gPlotCmd)
    subprocess.call(["gnuplot","temp.plt"])
    print(file)
在最后一个循环执行中,
子流程调用([“gnuplot”,“temp.plt”])
似乎没有执行。在程序结束时,temp.plt与上一次迭代的数据一起存在。另外,在最后一个循环中执行打印(文件)。此外,如果我绘制程序后留下的temp.plt,我将得到最后一个绘图(因此数据方面没有问题)。只有行
子流程调用([“gnuplot”,“temp.plt”])
未执行。我还尝试了popen和monitor stdout和stderr,但它们都是空的(就像在所有其他迭代中一样)。 该问题在linux和windows以及3.3.5和2.7.3版本中都会出现


我的结论是脚本有问题,但我不知道是什么原因。

这里一个可能的错误是,在运行gnuplot时,文件
temp.plt
实际上没有写入磁盘。Python不一定在调用writelines后立即刷新其缓冲区。这意味着当从在您的脚本中,它会看到一个空文件。它不会给出错误,因为空输入不是错误,并且它无法知道它还需要什么。当您在脚本之外运行它时,Python已经退出,因此不能再在自己的缓冲区中保存任何内容

使用
with
语句确保fw在完成后关闭:

with open('temp.plt', 'w') as fw:
    fw.writelines(gPlotCmd)

subprocess.call(["gnuplot","temp.plt"])

似乎我已经明白了。我缺少fw.close()。最后几行代码应该是:

fw = open('temp.plt','w+')
fw.writelines(gPlotCmd)
fw.close()
subprocess.call(["gnuplot","temp.plt"])
print(file)

现在代码生成了预期的绘图。

@lvc和您的答案是正确的;这是一个缓冲问题,
fw.flush()
应该可以解决它。但是您不需要临时文件,您可以直接将输入命令传递到
gnuplot
,而无需将它们写入磁盘:

from subprocess import Popen, PIPE

p = Popen('gnuplot', stdin=PIPE)
p.communicate(input=gPlotCmd.encode('ascii'))

lvc谢谢,我没有重新加载窗口,也没有看到您的答案,但是关闭的解决方案应该可以吗?