Pythonでコマンドライン引数を処理
コマンドラインオプションのパーザgetoptを使う。
from getopt import getopt, GetoptError try: opts, args = getopt(argv[1:], 'ab:', ['help', 'size=']) except GetoptError, e: # ヘルプメッセージを出力して終了 usage() sys.exit(2)
getoptの引数
getoptの第1引数は構文解析の対象になる引数リスト。基本的にsys.arg[1:] を渡す。
第2引数は1文字のオプション名。オプションが引数をとる場合(-b 10 や -f data.txtなど)はオプション指定文字の後に「:」をつける。
上の例では、オプションbのみ値をとることが出来る。aとbの両方が値をとるようにするときは'a:b:'と指定すればよい。
第3引数は複数文字のオプション名(省略可)。オプションが引数をとる場合はオプション文字列の後に「=」をつける。
getoptの返り値
2値のタプルを返す。
1つ目の要素は (オプション, それに対応する引数) という形式のタプルのリスト。
2つ目の要素は コマンドライン引数からオプションとそれに対応する引数を除去したもののリスト。
サンプルコード
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> args = s.split() >>> args ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'x', ['condition=', 'output-file=', 'testing']) >>> optlist [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x','')] >>> args ['a1', 'a2']