Pythonにはいろいろと便利なモジュールが揃っているし平易で読みやすいので、バッチ処理のスクリプトや簡単なCLIアプリケーションを書くのにかなり適しています。

僕もふだんからちょっとした処理を検証したりするのに使うのですが、その際に便利な機能とかをまとめてテンプレートにしているので紹介します。

あわせて読みたい:

特徴的な機能をいかに示します:

  • tracebackとloggingでエラー内容を表示
  • argparseでloggingのデバッグレベルを変更可能
  • logging.FileHandlerを追加すればファイルにログ書き出しも可
  • with time_logger(“hogeohoge”) と書くだけでそのwithブロックの処理時間が出力される(contextmanager使用)

ソースコード:

# coding: utf-8
import logging
import traceback
import argparse
import time
from contextlib import contextmanager

logger = logging.getLogger(__name__)


@contextmanager
def time_logger(label):
    start = time.time()
    yield
    end = time.time()
    logger.info("{}: {:.3f} sec consumed.".format(label, end - start))


def main(args):
    try:
        with time_logger("1.first_process"):
            print("Hello, world!")
    except Exception as e:
        logger.error(str(e) + ":" + traceback.format_exc())


if __name__ == '__main__':
    # args
    parser = argparse.ArgumentParser(
        description="Awesome CLI.")
    parser.add_argument(
        "-d", "--debug", action="store_true", help="Debug mode.")
    args = parser.parse_args()

    # logger
    if args.debug:
        LOG_LEVEL = logging.DEBUG
    else:
        LOG_LEVEL = logging.INFO
    formatter = logging.Formatter(
        fmt="[%(asctime)s] %(levelname)s [%(name)s/%(funcName)s() at line %(lineno)d]: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
    logger.setLevel(LOG_LEVEL)
    # stdout
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(LOG_LEVEL)
    logger.addHandler(stream_handler)
    main(args)

更新はgistでやっていきます:

もっと良くできるアイデア等ありましたらぜひご意見ください。

関連記事

fitbitの睡眠スコアを90弱で安定させる良い睡眠を続ける簡単な方法

m1 ipad pro 12.9 2021のusb-cハブはコレがベスト

Time Machine不要!Macを11.2.3にダウングレードして原神をm1 macbook airでプレイする

MH-Z19CとM5StickCで二酸化炭素濃度モニタリング

【神軽量HMD】Avegant Glyph 改造: 瓶詰堂さんのaltglyphを作った

PC、iPad、Android、switchもドックいらず!あまりに万能なusb-cハブが最強だった

コメント

コメントを返信する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です