Q: python では、コマンドライン引数をパースするには?
A: ArgumentParserを使う選択肢がありました。
下記のコードをみると後でみても説明はほぼ要らないでしょうと。
このパーサーは、引数をパースして辞書にしてくれます。
# !/usr/local/bin/python3
import argparse
parser = argparse.ArgumentParser(description = "description goes here")
parser.add_argument("-i", type=str, help = "help text goes here. This option is required", required=True)
parser.add_argument("-o", type=str, help = "help text goes here. This option is optional", required=False)
# command_arguments is dictinary
command_arguments = parser.parse_args()
ivariable = command_arguments.i
print(ivariable)
実行例もあれば、もっとわかりやすそう。
$ python3 test.py -i www
www
$ python3 test.py -i www -o asd
www
$ python3 test.py -i www -o
usage: test.py [-h] -i I [-o O]
test.py: error: argument -o: expected one argument
$ python3 test.py
usage: test.py [-h] -i I [-o O]
test.py: error: the following arguments are required: -i
$ python3 test.py -i
usage: test.py [-h] -i I [-o O]
test.py: error: argument -i: expected one argument
$