6.20.2.4 ヘルプを作成する

どのスクリプトでも使うことになる機能の最後の一つは、optparse の機能を使ったヘルプメッセージの生成です。やらなければならないことは、 オプションを追加する際に help 値を指定することだけです。 新たなパーザを作成し、ユーザに優しい (ドキュメント付きになっている) オプションを追加していきましょう:

usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=1,
                  help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", 
                  help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--file", dest="filename",
                  metavar="FILE", help="write output to FILE"),
parser.add_option("-m", "--mode",
                  default="intermediate",
                  help="interaction mode: one of 'novice', "
                       "'intermediate' [default], 'expert'")

optparse がコマンドラインの解析中に -h---help に遭遇するか、または単に parser.print_help() を呼び出すと、以下の内容を 標準出力に出力します:

usage: <yourscript> [options] arg1 arg2

options:
  -h, --help           show this help message and exit
  -v, --verbose        make lots of noise [default]
  -q, --quiet          be vewwy quiet (I'm hunting wabbits)
  -fFILE, --file=FILE  write output to FILE
  -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
                       [default], 'expert'

optparse に可能な限り親切なヘルプメッセージを出力させる 上で役に立つと思われることを以下にざっと述べます:

数多くのオプションを扱うときには、オプションをグループ化すると ヘルプメッセージ出力をよりよくする上で便利です。OptionParser は複数のオプショングループを収めることができ、各グループは 複数のオプションを収めることができます。

上で定義されたパーザに続けて OptionGroup を追加するのは 簡単です:

group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk."
                    "  It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

このコードは以下のヘルプ出力になります:

usage:  [options] arg1 arg2

options:
  -h, --help           show this help message and exit
  -v, --verbose        make lots of noise [default]
  -q, --quiet          be vewwy quiet (I'm hunting wabbits)
  -fFILE, --file=FILE  write output to FILE
  -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
                       [default], 'expert'

  Dangerous Options:
    Caution: use of these options is at your own risk.  It is believed that
    some of them bite.
    -g                 Group option.

ご意見やご指摘をお寄せになりたい方は、 このドキュメントについて... をご覧ください。