从Python调用gnuplot

22
我有一个 Python 脚本,经过一些计算后会生成两个格式为 gnuplot 输入的数据文件。
我该如何从 Python 中“调用” gnuplot?
我想将以下 Python 字符串作为输入发送到 gnuplot:
"plot '%s' with lines, '%s' with points;" % (eout,nout)

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

PS:我更喜欢不使用额外的Python模块(例如gnuplot-py),仅使用标准API。

谢谢你


你想使用 API 调用 gnuplot(它是用 C 编写的,所以你需要编写一些粘合代码,就像 gnuplot-py 中的那样),还是在 shell 中执行 "gnuplot" 命令? - Krzysztof Krasoń
只需在 shell 中执行 gnuplot。 - Andrei Ciobanu
8个回答

24

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

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

阅读了您的示例后,我编写了一个类似的函数,但不幸的是没有结果。(Popen = Popen,我相信这是一个打字错误,但这不是问题的原因) - Andrei Ciobanu
1
是的,POpen 是一个打字错误。除此之外,也许你需要指定 gnuplot 的完整路径或者添加你在另一条评论中提到的 '-persist' 开关。你还可以检查 plot.returncode 是否有错误。 - sth
1
对于收到“TypeError: a bytes-like object is required, not 'str'”错误的人:编码 - Herpes Free Engineer

18

在Doug Hellemann的Python Module of the Week中对Subprocess有非常清晰的解释。

这个很有效:

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
""")

2
如果你只想显示窗口而不让 Python 关闭它,可以使用 shell=False 和 gnuplot 的 --persist - sdaau

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')

6
谢谢,这个黑科技最终起作用了。 有一点需要提醒:system('gnuplot -persist tmp.gp') 是为了在脚本运行完后保留窗口。 - Andrei Ciobanu

7

我尝试做类似的事情,但是我想从Python中提取数据并将图形文件作为变量输出(因此数据和图形都不是实际文件)。这是我想出来的方法:

#! /usr/bin/env python

import subprocess
from sys import stdout, stderr
from os import linesep as nl

def gnuplot_ExecuteCommands(commands, data):
    args = ["gnuplot", "-e", (";".join([str(c) for c in commands]))]
    program = subprocess.Popen(\
        args, \
        stdin=subprocess.PIPE, \
        stdout=subprocess.PIPE, \
        stderr=subprocess.PIPE, \
        )
    for line in data:
        program.stdin.write(str(line)+nl)
    return program

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()
    plotProg = gnuplot_ExecuteCommands(commands, data)
    (out, err) = (plotProg.stdout, plotProg.stderr)
    stdout.write(out.read())

那个脚本在main函数的最后一步将图形输出到标准输出。等效的命令行(将图形管道传输至'out.gif')如下:

gnuplot -e "set datafile separator ','; set terminal gif; set output; plot '-' using 1:2 with linespoints, '' using 1:2 with linespoints" > out.gif
1,1
2,2
3,5
4,2
5,1
e
1,5
2,4
3,1
4,4
5,5
e

4

当我从celery任务计算图表时发现,从stdout读取数据会导致程序锁定。因此,我采用了Ben的建议,重新设计了代码,使用StringIO创建了将要输入到stdin的文件,并使用subprocess.communicate从stdout立即获取结果,无需读取。


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)

3

这里有一个提供wgnuplot.exe接口的类:

from ctypes import *
import time
import sys
import os

#
# some win32 constants
#
WM_CHAR     = 0X0102
WM_CLOSE    = 16
SW_HIDE     = 0
STARTF_USESHOWWINDOW = 1

WORD    = c_ushort
DWORD   = c_ulong
LPBYTE  = POINTER(c_ubyte)
LPTSTR  = POINTER(c_char) 
HANDLE  = c_void_p

class STARTUPINFO(Structure):
    _fields_ = [("cb",DWORD),
        ("lpReserved",LPTSTR), 
        ("lpDesktop", LPTSTR),
        ("lpTitle", LPTSTR),
        ("dwX", DWORD),
        ("dwY", DWORD),
        ("dwXSize", DWORD),
        ("dwYSize", DWORD),
        ("dwXCountChars", DWORD),
        ("dwYCountChars", DWORD),
        ("dwFillAttribute", DWORD),
        ("dwFlags", DWORD),
        ("wShowWindow", WORD),
        ("cbReserved2", WORD),
        ("lpReserved2", LPBYTE),
        ("hStdInput", HANDLE),
        ("hStdOutput", HANDLE),
        ("hStdError", HANDLE),]

class PROCESS_INFORMATION(Structure):
    _fields_ = [("hProcess", HANDLE),
        ("hThread", HANDLE),
        ("dwProcessId", DWORD),
        ("dwThreadId", DWORD),]

#
# Gnuplot
#
class Gnuplot:
    #
    # __init__
    #
    def __init__(self, path_to_exe):
        # open gnuplot
        self.launch(path_to_exe)
        # wait till it's ready
        if(windll.user32.WaitForInputIdle(self.hProcess, 1000)):
            print "Error: Gnuplot timeout!"
            sys.exit(1)
        # get window handles
        self.hwndParent = windll.user32.FindWindowA(None, 'gnuplot')
        self.hwndText = windll.user32.FindWindowExA(self.hwndParent, None, 'wgnuplot_text', None)



    #
    # __del__
    #
    def __del__(self):
        windll.kernel32.CloseHandle(self.hProcess);
        windll.kernel32.CloseHandle(self.hThread);
        windll.user32.PostMessageA(self.hwndParent, WM_CLOSE, 0, 0)


    #
    # launch
    #
    def launch(self, path_to_exe):
        startupinfo = STARTUPINFO()
        process_information = PROCESS_INFORMATION()

        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_HIDE

        if windll.kernel32.CreateProcessA(path_to_exe, None, None, None, False, 0, None, None, byref(startupinfo), byref(process_information)):
            self.hProcess = process_information.hProcess
            self.hThread = process_information.hThread
        else:
            print "Error: Create Process - Error code: ", windll.kernel32.GetLastError()
            sys.exit(1)



    #
    # execute
    #
    def execute(self, script, file_path):
        # make sure file doesn't exist
        try: os.unlink(file_path)
        except: pass

        # send script to gnuplot window
        for c in script: windll.user32.PostMessageA(self.hwndText, WM_CHAR, ord(c), 1L)

        # wait till gnuplot generates the chart
        while( not (os.path.exists(file_path) and (os.path.getsize(file_path) > 0))): time.sleep(0.01)

2

以下是一个扩展之前回答的示例。这个解决方案需要Gnuplot 5.1,因为它使用了数据块。有关数据块的更多信息,请在gnuplot中执行help datablocks。 一些先前方法的问题在于plot '-' 会立即消耗紧随其后的数据。不能在随后的绘图命令中重复使用相同的数据。可以使用数据块来缓解此问题。使用数据块,我们可以模拟多个数据文件。例如,您可能希望使用两个数据文件中的数据绘制图形,例如plot "myData.dat" using 1:2 with linespoints, '' using 1:3 with linespoints, "myData2.dat" using 1:2 with linespoints。我们可以将这些数据直接提供给gnuplot,而不需要创建实际的数据文件。

import sys, subprocess
from os import linesep as nl
from subprocess import Popen, PIPE


def gnuplot(commands, data):                                                    
  """ drive gnuplot, expects lists, returns stdout as string """  
  script= nl.join(data)+nl.join(commands)+nl
  print script
  args = ["gnuplot", "-p"]
  p = Popen(args, shell=False, stdin=PIPE)                       
  return p.communicate(script)[0]  

def buildGraph():
  commands = [\
      "set datafile separator ','",\
      "plot '$data1' using 1:2 with linespoints, '' using 1:3 with linespoints, '$data2' using 1:2 with linespoints",\
      ]
  data = [\
      "$data1 << EOD",\
      "1,30,12",\
      "2,40,15",\
      "3,35,20",\
      "4,60,21",\
      "5,50,30",\
      "EOD",\
      "$data2 << EOD",\
      "1,20",\
      "2,40",\
      "3,40",\
      "4,50",\
      "5,60",\
      "EOD",\
      ]

  return (commands, data)  


def main(args):
  (commands, data) = buildGraph()
  print gnuplot(commands, data)


if __name__ == "__main__":
   main(sys.argv[1:])

这种方法比plot '-'更加灵活,因为它使得多次重复使用相同的数据变得更加容易,包括在同一条绘图命令中:https://dev59.com/imPVa4cB1Zd3GeqP4lN4#33064402请注意,这种方法要求在绘图命令之前将数据提供给gnuplot
此外,我没有像@ppetraki那样使用IOString,因为显然这比简单的列表连接器慢:https://waymoot.org/home/python_string/

数据中的值必须不带逗号进行编写。列之间用空格分隔,如gnuplot帮助中所述。在Python3中,您还必须对字符串脚本进行编码:return p.communicate(script.encode('utf-8'))[0] - terence hill
@terencehill 这不是真的:只要您指定命令 set datafile separator ',',您可以使用任何分隔符,参见我上面的示例。 - Joris Kinable
抱歉,我更改了命令并错过了引用分隔符的行。 - terence hill

2

我来晚了,但因为让它正常工作花费了我一些时间,也许值得做个记录。这些程序在Windows上使用Python 3.3.2运行。

请注意,程序中到处都使用字节而不是字符串(例如b"plot x",而不仅仅是"plot x"),但如果这是个问题,只需执行类似以下的操作即可:

"plot x".encode("ascii")

第一种解决方案:使用communicate发送所有内容,并在完成后关闭。不要忘记pause,否则窗口会立即关闭。但是,如果使用gnuplot将图像存储在文件中,则没有问题。

from subprocess import *
path = "C:\\app\\gnuplot\\bin\\gnuplot"
p = Popen([path], stdin=PIPE, stdout=PIPE)
p.communicate(b"splot x*y\npause 4\n")

第二种解决方案:使用stdin.write(...)一个接一个地发送命令,但是不要忘记刷新!(这是我最初没有做对的地方)并且在工作完成后使用terminate关闭连接和gnuplot。

from subprocess import *
path = "C:\\app\\gnuplot\\bin\\gnuplot"
p = Popen([path], stdin=PIPE, stdout=PIPE)

p.stdin.write(b"splot x*y\n")
p.stdin.flush()
...
p.stdin.write(b"plot x,x*x\n")
p.stdin.flush()
...
p.terminate()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接