2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

グラフ表示とともにファイル名に時間を付けて保存するデコレータ

2
Last updated at Posted at 2019-07-07

目的

  • デコレータの使い方を初めて勉強したので記録する。
  • 練習のために、グラフを書くときに便利になる機能を考えて実装してみた
  • グラフ表示と同時にファイル名に接頭字と時間を付けて保存する

ポイント

  • デコレータの使いどころとしては、hogehogeってよくやるけど、ついでにXXXの処理もいつもやってるなぁって時
  • 自作モジュール(decorator_utility.py)にデコレータを作成し、いつでも呼び出せるようにしておけば@XXXXでお手軽に使える。ベンリー!

コード

デコレータの実装

decorator_utility.py

import datetime

def save_deco(name): #デコレータの引数でファイル名の接頭字を定義する
    def __save_deco(func): # 描画関数を持ってくる
        def wrapper(*arg, **kwargs):
            now = datetime.datetime.now() #保存時間の設定
            fig_img = func(*arg, **kwargs) #描画関数の実行
            return fig_img.savefig('{0}_{1:%Y%m%d%H%M%S}'.format(name, now)) #メインの処理
        return wrapper # 関数名が返り値
    return __save_deco # 関数名が返り値

処理系

main.py

import numpy as np
import random
import matplotlib.pyplot as plt
from decorator_utility import save_deco

# プロットする値を適当に
x = np.array([random.randint(0, 10) for i in range(10)])
y = np.array([random.randint(8, 12) for i in range(10)])


@save_deco('new_graph')
def drow_graph(x_data,y_data):
    fig, ax = plt.subplots()
    ax.plot(x_data, y_data, 'o')
    return fig


drow_graph(x, y)

CWDにファイルが出来ている。迷子になったらos.getcwd()

参考にさせていただきました

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?