argparseを便利に使う

コマンドライン引数

コマンドライン引数を使いたいですよね。
そんなときは argparse です。
argparse --- コマンドラインオプション、引数、サブコマンドのパーサー

基本的な使い方は、これです。
type はいろいろ設定できます。

Python

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--value_01', default=2, type=int, help='value #1')
    parser.add_argument('--value_02', default=4.5, type=float, help='value #2')
    parser.add_argument('--value_03', default='aaa', type=str, help='value #3')
        
    args = parser.parse_args()
    print(args)
    print(type(args))
    # Namespace(value_01=2, value_02=4.5, value_03='aaa')
    # <class 'argparse.Namespace'>
    
    print(args.value_01)
    print(args.value_02)
    print(args.value_03)
    # 2
    # 4.5
    # aaa
    
    # 辞書型に変換できる。
    print(vars(args))
    print(type(vars(args)))
    # {'value_01': 2, 'value_02': 4.5, 'value_03': 'aaa'}
    # <class 'dict'>

もっと便利に使う

choices

コマンドライン引数をいくつかの選択肢の中から選べるようにすることができます。
choices

test_choices.py

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--mode',
        default='default',
        type=str,
        choices=['fast', 'slow'],
        help='exec mode',
        )
    
    args = parser.parse_args()
    print(args.mode)
$ python test_choices.py --mode slow
slow

選択肢に無い単語を使うと、エラーになります。

$ python test_choices.py --mode middle
usage: test_choices.py [-h] [--mode {fast,slow}] test_choices.py: error: argument --mode: invalid choice: 'middle' (choose from 'fast', 'slow')

required

指定したパラメータの入力を必須にすることができます。
required

test_choices.py

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--mode',
        default='default',
        type=str,
        choices=['fast', 'slow'],
        required=True,
        help='exec mode',
        )
    
    args = parser.parse_args()
    print(args.mode)
$ python test_choices.py --mode fast
fast

必須パラメータの入力が無い場合は、エラーになります。

$ python test_choices.py
usage: test_choices.py [-h] --mode {fast,slow}
test_choices.py: error: the following arguments are required: --mode

action

action は、コマンドライン引数でオプションが設定されたときに、何をするか、指定できます。
action

最も使う action が 'store_true', 'store_false' です。
これらは、パラメータに、それぞれ True と False を格納するというものです。

test_action.py

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--display',
        default=False,
        action='store_true',
        help='force display',
        )
    
    args = parser.parse_args()
    print(args)
    if args.display:
        print(args.display)
$ python test_action.py
Namespace(display=False)

コマンドラインでオプションを設定してみます。

$ python test_action.py --display
Namespace(display=True)
True

短いオプション

ツールとして提供するときは、オプションを短くしたくなります。
短いオプションにすることも可能です。
short-options

test_action2.py

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-d',
        '--display',
        default=False,
        action='store_true',
        help='force display',
        )
    
    args = parser.parse_args()
    print(args)
    if args.display:
        print(args.display)
$ python3 test_action.py -d
Namespace(display=True)
True

help

最後に --help です。

$ python test_action.py -h
usage: test_action.py [-h] [-d]

optional arguments:
-h, --help show this help message and exit
-d, --display force display