21

我有一个 python 脚本,经过一些计算后会生成两个格式化为 gnuplot 输入的数据文件。

如何从 python 中“调用”gnuplot?

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

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

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

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

谢谢你

4

8 回答 8

23

subprocess模块允许您调用其他程序:

import subprocess
plot = subprocess.Popen(['gnuplot'], stdin=subprocess.PIPE)
plot.communicate("plot '%s' with lines, '%s' with points;" % (eout,nout))
于 2010-01-29T12:48:52.320 回答
16

在 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

也可以使用“通信”,但绘图窗口会立即关闭,除非使用 gnuplot pause 命令

proc.communicate("""
set xrange [0:10]; set yrange [-2:2]
plot sin(x)
pause 4
""")
于 2011-02-15T10:43:21.283 回答
10

一种简单的方法可能是只编写包含 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')
于 2010-01-29T13:11:02.283 回答
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())

该脚本将图形转储到 stdout 作为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
于 2011-04-22T13:23:42.810 回答
4

当我从芹菜工作中计算图表时,我接受了 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)
于 2014-02-07T16:35:58.420 回答
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)
于 2011-06-15T11:09:46.250 回答
2

我有点晚了,但由于我花了一些时间让它工作,也许值得记一下。这些程序在 Windows 上使用 Python 3.3.2。

请注意,到处都使用字节,而不是字符串(例如 b“plot x”,而不仅仅是“plot x”),但如果出现问题,只需执行以下操作:

"plot x".encode("ascii")

第一个解决方案:使用通信发送所有内容,并在完成后关闭。千万不要忘记暂停,否则窗口会立即关闭。但是,如果使用 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(...) 一个接一个地发送命令。但是,不要忘记冲洗!(这是我一开始没有做对的)并在工作完成后使用终止来关闭连接和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()
于 2013-08-07T08:27:25.883 回答
2

这是另一个示例,它扩展了之前的一些答案。该解决方案需要 Gnuplot 5.1,因为它使用数据块。有关数据块的更多信息,请help datablocks在 gnuplot 中执行。以前的一些方法的问题是,它会plot '-'立即消耗紧跟在 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 ://stackoverflow.com/a/33064402/895245 请注意,这种方法要求数据是在绘图命令之前喂给gnuplot

此外,我没有像@ppetraki 那样使用 IOString,因为显然这比简单的列表连接器慢:https ://waymoot.org/home/python_string/

于 2017-06-27T18:21:10.140 回答