从Python调用gnuplot

22 投票
8 回答
49276 浏览
提问于 2025-04-15 18:38

我有一个Python脚本,经过一些计算后会生成两个数据文件,这些文件的格式是gnuplot可以识别的。

我该如何在Python中“调用”gnuplot呢?

我想把下面这个Python字符串作为输入发送给gnuplot:

"plot '%s' with lines, '%s' with points;" % (eout,nout)

其中‘eout’和‘nout’是这两个文件的名字。

附注:我更喜欢不使用额外的Python模块(比如gnuplot-py),只用标准的API。

谢谢!

8 个回答

18

Doug Hellemann的Python每周模块对子进程的解释非常清晰。

这个方法效果很好:

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
proc.stdin.flush()

你也可以使用'communicate',但是如果不使用gnuplot的暂停命令,绘图窗口会立刻关闭。

proc.communicate("""
set xrange [0:10]; set yrange [-2:2]
plot sin(x)
pause 4
""")
24

subprocess模块可以让你调用其他程序:

import subprocess
plot = subprocess.Popen(['gnuplot'], stdin=subprocess.PIPE)
plot.communicate("plot '%s' with lines, '%s' with points;" % (eout,nout))
12

一种简单的方法是,先写一个第三个文件,把你的gnuplot命令放进去,然后告诉Python去执行这个文件里的gnuplot命令。比如,你可以把

"plot '%s' with lines, '%s' with points;" % (eout,nout)

写入一个叫做tmp.gp的文件中。然后你可以使用

from os import system, remove
system('gnuplot -persist tmp.gp')
remove('tmp.gp')

撰写回答