LoginSignup
1
0

More than 5 years have passed since last update.

Pythonでコマンドライン引数を自作したい

Last updated at Posted at 2018-12-03

背景

  • Pythonのスクリプトを実行するときに、コマンドライン引数の有無によって処理を分岐させたい

使用するライブラリ

サンプルコード

実行させるpythonファイル

script.py
# 1. ライブラリインポート
import argparse

# 2.コマンドラインオプションパーサーのインスタンス化
parser = argparse.ArgumentParser()

# 3.コマンドラインオプションの追加(bool)
## action='store_true' は 'オプションがあると'True'になりますよ' の意
parser.add_argument('-a','--auto', action='store_true', default=False, help='use only when you want execute with regularly')
args = parser.parse_args()

# 追加されたオプションは 'args.[オプション名] に格納されている'
if args.auto:
    print('auto!!!')
else:
    print('not-auto!!!')

# more code...

実行時のコマンドと出力結果

# コマンドラインオプションなし
$ python script.py
not-auto!!!

# コマンドラインオプションあり(-a)
$ python script.py -a
auto!!!

# コマンドラインオプションあり(--auto)
$ python script.py --auto
auto!!!

# 定義していないコマンドラインオプション
$ python script.py --none
usage: script.py [-h] [-a]
script.py: error: unrecognized arguments: --none

# コマンドラインオプション一覧を見たい時
$ python script.py -h
usage: script.py [-h] [-a]

optional arguments:
  -h, --help  show this help message and exit
  -a, --auto  use only when you want execute with regularly # parser.add_argument(help='') で定義したメッセージ

こんな感じで使いたい

  • 手動で実行させるときはユーザーに日付を手入力させて、そこを基準日として処理する
  • 定期実行(cronなど)に仕込むときには -a オプションをつけて実行日を基準日として処理する
1
0
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
1
0