/>
小さな工夫と発見の蓄積
[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
ただいまコメントを受けつけておりません。
Pythonでのオプション処理には、ずっとgetoptライブラリを使ってきたが、今日、argparse
というライブラリの存在を知り、使ってみたところ大分使いやすかった。公式の解説がとても丁寧なのでより詳しくはそちらを参照。
ポイント
* まずはparser
オブジェクトを作り、これにどんどん引数やオプションを追加していく。
* -h
, --help
オプションは自動に追加される(!)
* add_argument
で引数・オプションを追加していく。オプションには「-」をつけて区別する。
* 値のタイプを指定できる。
* 値を取らないオプションには、action='store_true'
をつけて区別する。
* 入力値は全てparse_args()
のインスタント変数として得られる (下の例ではargs
に格納)。
* オプションの付け方が複数通りある時は、どれか1つが変数名になる。下の例では、「args.subtract
」を「args.s
」に変えるとエラーになる。「-s
」でも「--subtract
」をオプションを指定できるが、名前は「subtract
」だけになるらしい。
* 少し試した限り、長い名前があるならそのうちの1つめが選ばれ、長い名前がなければ1文字オプションの1つめが選ばれるようだ。実用的には、長い名前が優先される、と覚えればよい。
import argparse parser = argparse.ArgumentParser(description='damn calculator') # necessary arguments parser.add_argument('x', type=int, help='first number') parser.add_argument('y', type=int, help='second number') # options with value parser.add_argument('-t', type=int, help='how many times', default=1) # options with no value parser.add_argument('-s', '--subtract', action='store_true') parser.add_argument('-m', '--multiply', action='store_true') parser.add_argument('-d', '--divide', action='store_true') # parse inputs args = parser.parse_args() # values are stored as the attributes of the args object x = args.x y = args.y for _ in range(args.t): print x + y, if args.subtract: print x - y, if args.multiply: print x * y, if args.divide: print float(x) / y, print ''
$ python calc.py -h usage: calc.py [-h] [-t T] [-s] [-m] [-d] x y damn calculator positional arguments: x first number y second number optional arguments: -h, --help show this help message and exit -t T how many times -s, --subtract -m, --multiply -d, --divide $ python calc.py 3 6 9 $ python calc.py -t 3 -smd 3 7 10 -4 21 0.428571428571 10 -4 21 0.428571428571 10 -4 21 0.428571428571