Python Subprocess.call() Invoking Gnuplot Then Evince On A Newly Created File Sometimes Has No Output
I've been trying to use Python 3.4 to call a simple gnuplot script and then display the result (a .ps file) using evince. My code looks like this: plotfile = 'plot.p' with open(pl
Solution 1:
I believe you've had some misleading test results leading you down the wrong path. Using subprocess.call()
or calling .wait()
on a Popen
object does genuinely wait for the program that was invoked to exit. What's not guaranteed, however, is whether the result of your plt.writelines()
calls will be flushed to disk or will still be in an in-memory buffer by the time gnuplot
is started.
Given the following code:
plotfile = "plot.p"withopen(plotfile, "w") as plt:
lines = ['set term postscript',
'set output "speed.ps"',
'set xlabel "Time"',
'set ylabel "Speed"',
"plot '{}' u 2:4 title 'speed' with lines".format(infile)
]
lines = map(lambda x: x + '\n', lines)
plt.writelines(lines)
plt.flush() ### <-- EITHER CALL THIS OR MOVE THE BELOW OUTSIDE THE with BLOCK# Call gnuplot and evince
subprocess.call(['gnuplot', plotfile])
subprocess.call(['evince', 'speed.ps'])
...absent the flush()
, the plt
file isn't guaranteed to have all contents flushed before subprocess.call()
is invoked; lines can still be buffered and not available to other programs yet.
Closing a file flushes it, so moving the call()
s outside the with
block will also solve your problem.
Post a Comment for "Python Subprocess.call() Invoking Gnuplot Then Evince On A Newly Created File Sometimes Has No Output"