バージョン2.3 以降で新規追加された 仕様です。
optparse モジュールは、Python による強力で柔軟、拡張性があり 簡単に利用できるコマンドライン解析ライブラリです。 optparse を使うことで、有能で洗練されたコマンドラインオプションの 解析機能を少ない労力でスクリプトに追加できます。
以下は optparse を使っていくつかのコマンドラインオプション を簡単なスクリプトに追加する例です:
from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=1, help="don't print status messages to stdout") (options, args) = parser.parse_args()
このようにわずかな行数のコードによって、スクリプトのユーザは コマンドライン上で以下のような "よくある使い方" を実行できるように なります:
$ <yourscript> -f outfile --quiet $ <yourscript> -qfoutfile $ <yourscript> --file=outfile -q $ <yourscript> --quiet --file outfile
(これらの結果は全て options.filename == "outfile"
および
options.verbose == 0
...つまり予想していた結果となります)
もっと気の利いたことに、ユーザは
$ <yourscript> -h $ <yourscript> --help
usage: <yourscript> [options] options: -h, --help show this help message and exit -fFILE, --file=FILE write report to FILE -q, --quiet don't print status messages to stdout
以上は optparse がコマンドライン解析に与える柔軟性のほんの 一部にすぎません。