Saturday 18 May 2013

gnuplot (10)

臆面もなく前のを使いまわした.
今回は「そういえば python とかから gnuplot を呼びたいぞ!」なおはなし.
#あれどっちかというと python よりな記事では………
今回は画像ないです.ごめんなさい.
せっかちな方は Calling gnuplot from python - Stack Overflow をどうぞ.
Cな人は gnuplot - Making C code plot a graph automatically - Stack Overflow とかでしょうか.


python とかから gnuplot を呼びたい.
目的によってはというか単に $ gnuplot --persist foo.plt
が面倒なだけなら,shell script で済ますのは手.bar.py foo.pltができるとすると
#!/bin/sh
bar.py
gnuplot --persist foo.plt
(これで適当なファイル名で保存して chmod で実行権限つけて ./ファイル名 !)
ここで -persist さんのおかげで plot したあとのウインドウが終了後も消えません.
2つめの手は osモジュールから呼び出すというやつ.
plot したい内容を temp.pltにでも保存しといて呼びだそう.ファイル作らずとも
$ echo "plot sin(x)" | gnuplot -persist
でも多分同じことなのでそれで.
#!/usr/bin/python
from os import system
system('echo "plot sin(x)" | gnuplot --persist')
でだいじょうぶ.
ところでこの os.system で呼んだコマンドが普段標準出力に流してくれる内容を読み込みたい場合は
import commands
commands.getoutput("hoge")
とやれば良いようです.単純に
from os import system
a = system("ls")
print a
とかにすると「成功したぜドヤァ」な気分で(?) 0 を返してくれます.
system("ls file-that-does-not-exist") なら 512 とかそんなかんじ.

そして今回のメインは次のsubprocessモジュールを使うというもの.
とはいえ何が起こってるのかいまいちわかってないのですが.
Calling gnuplot from python - Stack Overflow を参考に,

#via-subprocess.py
import subprocess
plot = subprocess.Popen(['/usr/bin/gnuplot', '--persist'],stdin = subprocess.PIPE)
plot.stdin.write("plot sin(x)\n") #\n 忘れないようにねー
plot.stdin.write("replot cos(x)\n")
plot.stdin.write("exit\n")
みたいな感じ.
17.1. subprocess — Subprocess management — Python v2.7.5 documentation には
stdin.write とかより communicate使ったほうがええで
みたいなことが書いてあるのですが,communicateでこのように命令を二回に分けて渡そうとすると
ValueError: I/O operation on closed file
っていって怒られてしまうので,とりあえずここでは stdin.write使ってます. うーん,なんと言うかもうちょっと何をやってるのかわかるべきですがそのへんはまた今度.
ともかくこういう感じで gnuplot 呼べると夢が広がりますね.
#最初このコードを誤って subprocess.py っていう名前で保存してて当然
#/usr/lib/python2.7/subprocess.py じゃなくて ./subprocess.py が読み込まれて
#AttributeError: 'module' object has no attribute
#って怒られましたとさ. 恥ずかし.
ちなみに今回の記事はCによる数値計算とシミュレーション (CiNii)という本のコードで
C から gnuplot 呼び出してるのを見て,みたいな感じでした.
ここでもパイプ作って云々してるみたいですが,詳しくは来ないかもしれない続報を待て.

No comments:

Post a Comment