ナンクル力学系

学んだ事を書き連ねていこう。

id:salamannのためのpython講座〜勝手に添削してみた編〜

leave a comment »

あまりにうんこで恥ずかしいvv」と言われたけれど書く(ぉ

送られてきたコードはgnuplotのバッチファイルを生成するスクリプト:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys

min=400000
max=750000
dt=400
run="601"
runn="09"

fo=file(r"gnu_py.f90","w")
fo.write("set size square\n")
fo.write("set ylabel \"Static Pressure kPa\"\n")
fo.write("set xlabel \"Time second\"\n")
fo.write("set yrange [0:200]\n")
fo.write("set grid\n\n")
fo.write("set term png large font \"Helvetica\"\n")
for i in range(min,max,dt):
    fo.write("set out \"cycle%d.png\"\n"%(i))
    fo.write("plot \""+run+"_pr.csv\" u 1:2 every ::%d::%d w l t \"RUN"%(i,i+dt)+runn+"kp1\"")
    fo.write(",\""+run+"_pr.csv\" u 1:3 every ::%d::%d w l t \"RUN"%(i,i+dt)+runn+"kp2\"")
    fo.write(",\""+run+"_pr.csv\" u 1:4 every ::%d::%d w l t \"RUN"%(i,i+dt)+runn+"kp3\"")
    fo.write(",\""+run+"_pr.csv\" u 1:5 every ::%d::%d w l t \"RUN"%(i,i+dt)+runn+"kp4\"\n")
    fo.write("set out\n")
#    fo.write("set term windows\n")
#    fo.write(" \n")
fo.write("set term windows\n")
fo.close()

アドバイス:

  1. fo.wirteを毎回呼び出すより文字列に書き出してから一気に書き込んだ方が見やすいと思うよ!
  2. python文字列のrawモードを利用したら,「\”」とか書かずに「\」を書けるよ!
  3. +で文字列繋ぐより,”%s”使うのがいいらしいよ!

俺が書くとしたらこんな感じかな:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys

min=400000
max=750000
dt=400
run="601"
runn="09"

cmd = """\
set size square
set ylabel "Static Pressure kPa"
set xlabel "Time second"
set yrange [0:200]
set grid

set term png large font "Helvetica"
"""

plot_i = r"""
set out "cycle%(i)d.png"
plot\
  "%(run)s_pr.csv" u 1:2 every ::%(i)d::%(j)d w l t "RUN%(runn)skp1",\
  "%(run)s_pr.csv" u 1:3 every ::%(i)d::%(j)d w l t "RUN%(runn)skp2",\
  "%(run)s_pr.csv" u 1:4 every ::%(i)d::%(j)d w l t "RUN%(runn)skp3",\
  "%(run)s_pr.csv" u 1:5 every ::%(i)d::%(j)d w l t "RUN%(runn)skp4"
set out
"""

for i in range(min,max,dt):
    cmd += plot_i % { "i":i, "j":i+dt, "run":run, "runn":runn }

## print cmd
fo=file(r"gnu_py.f90","w")
fo.write(cmd)
fo.close()

参考:

Advertisements

Written by tkf

January 15, 2009 at 4:10 pm

Posted in PC

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: