Calling gnuplot from python

前端 未结 8 639
清酒与你
清酒与你 2020-12-04 18:34

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

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 18:59

    I am a bit late, but since it took me some time to make it work, maybe it's worth putting a note. The programs are working with Python 3.3.2 on Windows.

    Notice that bytes are used everywhere, not strings (e.g. b"plot x", not simply "plot x"), but in case it's a problem, simply do something like:

    "plot x".encode("ascii")
    

    First solution: use communicate to send everything, and close when it's done. One must not forget pause, or the window is closed at once. However, it's not a problem if gnuplot is used to store images in files.

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

    Second solution: send commands one after another, using stdin.write(...). But, don't forget flush! (this is what I didn't get right at first) And use terminate to close the connection and gnuplot when the job is done.

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

提交回复
热议问题