I\'ve a python script that after some computing will generate two data files formatted as gnuplot input.
How do I \'call\' gnuplot from python ?
I want to se
Subprocess is explained very clearly on Doug Hellemann's Python Module of the Week
This works well:
import subprocess
proc = subprocess.Popen(['gnuplot','-p'],
shell=True,
stdin=subprocess.PIPE,
)
proc.stdin.write('set xrange [0:10]; set yrange [-2:2]\n')
proc.stdin.write('plot sin(x)\n')
proc.stdin.write('quit\n') #close the gnuplot window
One could also use 'communicate' but the plot window closes immediately unless a gnuplot pause command is used
proc.communicate("""
set xrange [0:10]; set yrange [-2:2]
plot sin(x)
pause 4
""")
I went with Ben's suggestion as I was computing charts from a celery job and found that it would lockup when reading from stdout. I redesigned it like so using StringIO to create the file destined for stdin and subprocess.communicate to get the result immediately via stdout, no read required.
from subprocess import Popen, PIPE
from StringIO import StringIO
from os import linesep as nl
def gnuplot(commands, data):
""" drive gnuplot, expects lists, returns stdout as string """
dfile = StringIO()
for line in data:
dfile.write(str(line) + nl)
args = ["gnuplot", "-e", (";".join([str(c) for c in commands]))]
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
dfile.seek(0)
return p.communicate(dfile.read())[0]
def gnuplot_GifTest():
commands = [\
"set datafile separator ','",\
"set terminal gif",\
"set output",\
"plot '-' using 1:2 with linespoints, '' using 1:2 with linespoints",\
]
data = [\
"1,1",\
"2,2",\
"3,5",\
"4,2",\
"5,1",\
"e",\
"1,5",\
"2,4",\
"3,1",\
"4,4",\
"5,5",\
"e",\
]
return (commands, data)
if __name__=="__main__":
(commands, data) = gnuplot_GifTest()
print gnuplot(commands, data)