从python调用gnuplot

2024-05-21 03:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,在一些计算之后,它将生成两个格式为gnuplot输入的数据文件。

如何从python“调用”gnuplot?

我想将以下python字符串作为输入发送到gnuplot:

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

其中,'eout'和'nout'是两个文件名。

附言: 我宁愿不使用额外的python模块(例如gnuplot py),只使用标准API。

谢谢你


Tags: 模块字符串py脚本plot文件名数据文件格式
3条回答

子流程在Doug Hellemann的 Python Module of the Week

这很有效:

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

也可以使用“communicate”,但除非使用gnuplot pause命令,否则绘图窗口将立即关闭

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

一个简单的方法可能是编写包含gnuplot命令的第三个文件,然后告诉Python使用该文件执行gnuplot。说你写了

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

发送到一个名为tmp.gp的文件。那你就可以用

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

^{}模块允许您调用其他程序:

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

相关问题 更多 >