"optparse" --- Parser for command line options
**********************************************

**ソースコード:** Lib/optparse.py

======================================================================


Choosing an argument parsing library
====================================

The standard library includes three argument parsing libraries:

* "getopt": a module that closely mirrors the procedural C "getopt"
  API. Included in the standard library since before the initial
  Python 1.0 release.

* "optparse": a declarative replacement for "getopt" that provides
  equivalent functionality without requiring each application to
  implement its own procedural option parsing logic. Included in the
  standard library since the Python 2.3 release.

* "argparse": a more opinionated alternative to "optparse" that
  provides more functionality by default, at the expense of reduced
  application flexibility in controlling exactly how arguments are
  processed. Included in the standard library since the Python 2.7 and
  Python 3.2 releases.

In the absence of more specific argument parsing design constraints,
"argparse" is the recommended choice for implementing command line
applications, as it offers the highest level of baseline functionality
with the least application level code.

"getopt" is retained almost entirely for backwards compatibility
reasons. However, it also serves a niche use case as a tool for
prototyping and testing command line argument handling in
"getopt"-based C applications.

"optparse" should be considered as an alternative to "argparse" in the
following cases:

* an application is already using "optparse" and doesn't want to risk
  the subtle behavioural changes that may arise when migrating to
  "argparse"

* the application requires additional control over the way options and
  positional parameters are interleaved on the command line (including
  the ability to disable the interleaving feature completely)

* the application requires additional control over the incremental
  parsing of command line elements (while "argparse" does support
  this, the exact way it works in practice is undesirable for some use
  cases)

* the application requires additional control over the handling of
  options which accept parameter values that may start with "-" (such
  as delegated options to be passed to invoked subprocesses)

* the application requires some other command line parameter
  processing behavior which "argparse" does not support, but which can
  be implemented in terms of the lower level interface offered by
  "optparse"

These considerations also mean that "optparse" is likely to provide a
better foundation for library authors writing third party command line
argument processing libraries.

As a concrete example, consider the following two command line
argument parsing configurations, the first using "optparse", and the
second using "argparse":

   import optparse

   if __name__ == '__main__':
       parser = optparse.OptionParser()
       parser.add_option('-o', '--output')
       parser.add_option('-v', dest='verbose', action='store_true')
       opts, args = parser.parse_args()
       process(args, output=opts.output, verbose=opts.verbose)

   import argparse

   if __name__ == '__main__':
       parser = argparse.ArgumentParser()
       parser.add_argument('-o', '--output')
       parser.add_argument('-v', dest='verbose', action='store_true')
       parser.add_argument('rest', nargs='*')
       args = parser.parse_args()
       process(args.rest, output=args.output, verbose=args.verbose)

The most obvious difference is that in the "optparse" version, the
non-option arguments are processed separately by the application after
the option processing is complete. In the "argparse" version,
positional arguments are declared and processed in the same way as the
named options.

However, the "argparse" version will also handle some parameter
combination differently from the way the "optparse" version would
handle them. For example (amongst other differences):

* supplying "-o -v" gives "output="-v"" and "verbose=False" when using
  "optparse", but a usage error with "argparse" (complaining that no
  value has been supplied for "-o/--output", since "-v" is interpreted
  as meaning the verbosity flag)

* similarly, supplying "-o --" gives "output="--"" and "args=()" when
  using "optparse", but a usage error with "argparse" (also
  complaining that no value has been supplied for "-o/--output", since
  "--" is interpreted as terminating the option processing and
  treating all remaining values as positional arguments)

* supplying "-o=foo" gives "output="=foo"" when using "optparse", but
  gives "output="foo"" with "argparse" (since "=" is special cased as
  an alternative separator for option parameter values)

Whether these differing behaviors in the "argparse" version are
considered desirable or a problem will depend on the specific command
line application use case.

参考:

  click is a third party argument processing library (originally based
  on "optparse"), which allows command line applications to be
  developed as a set of decorated command implementation functions.

  Other third party libraries, such as typer or msgspec-click, allow
  command line interfaces to be specified in ways that more
  effectively integrate with static checking of Python type
  annotations.


はじめに
========

"optparse" is a more convenient, flexible, and powerful library for
parsing command-line options than the minimalist "getopt" module.
"optparse" uses a more declarative style of command-line parsing: you
create an instance of "OptionParser", populate it with options, and
parse the command line. "optparse" allows users to specify options in
the conventional GNU/POSIX syntax, and additionally generates usage
and help messages for you.

Here's an example of using "optparse" in a simple script:

   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=True,
                     help="don't print status messages to stdout")

   (options, args) = parser.parse_args()

このようにわずかな行数のコードによって、スクリプトのユーザはコマンドラ
イン上で例えば以下のような「よくある使い方」を実行できるようになります
:

   <yourscript> --file=outfile -q

As it parses the command line, "optparse" sets attributes of the
"options" object returned by "parse_args()" based on user-supplied
command-line values.  When "parse_args()" returns from parsing this
command line, "options.filename" will be ""outfile"" and
"options.verbose" will be "False".  "optparse" supports both long and
short options, allows short options to be merged together, and allows
options to be associated with their arguments in a variety of ways.
Thus, the following command lines are all equivalent to the above
example:

   <yourscript> -f outfile --quiet
   <yourscript> --quiet --file outfile
   <yourscript> -q -foutfile
   <yourscript> -qfoutfile

さらに、ユーザが以下のいずれかを実行すると

   <yourscript> -h
   <yourscript> --help

and "optparse" will print out a brief summary of your script's
options:

   Usage: <yourscript> [options]

   Options:
     -h, --help            show this help message and exit
     -f FILE, --file=FILE  write report to FILE
     -q, --quiet           don't print status messages to stdout

*yourscript* の中身は実行時に決まります (通常は "sys.argv[0]" になりま
す)。


背景
====

"optparse" was explicitly designed to encourage the creation of
programs with straightforward command-line interfaces that follow the
conventions established by the "getopt()" family of functions
available to C developers. To that end, it supports only the most
common command-line syntax and semantics conventionally used under
Unix.  If you are unfamiliar with these conventions, reading this
section will allow you to acquaint yourself with them.


用語集
------

引数 (argument)
   コマンドラインでユーザが入力するテキストの塊で、シェルが "execl" や
   "execv" に引き渡すものです。Python では、引数は "sys.argv[1:]" の要
   素となります。("sys.argv[0]" は実行しようとしているプログラムの名前
   です。引数解析に関しては、この要素はあまり重要ではありません。)
   Unix シェルでは、「語 (word)」という用語も使います。

   場合によっては "sys.argv[1:]" 以外の引数リストを代入する方が望まし
   いことがあるので、「引数」は「 "sys.argv[1:]" または "sys.argv[1:]"
   の代替として提供される別のリストの要素」と読むべきでしょう。

オプション (option)
   an argument used to supply extra information to guide or customize
   the execution of a program.  There are many different syntaxes for
   options; the traditional Unix syntax is a hyphen ("-") followed by
   a single letter, e.g. "-x" or "-F".  Also, traditional Unix syntax
   allows multiple options to be merged into a single argument, e.g.
   "-x -F" is equivalent to "-xF".  The GNU project introduced "--"
   followed by a series of hyphen-separated words, e.g. "--file" or "
   --dry-run".  These are the only two option syntaxes provided by
   "optparse".

   他に見られる他のオプション書法には以下のようなものがあります:

   * ハイフンの後ろに数個の文字が続くもので、例えば "-pf" (このオプシ
     ョンは複数のオプションを一つにまとめたものとは *違います*)

   * ハイフンの後ろに語が続くもので、例えば "-file" (これは技術的には
     上の書式と同じですが、通常同じプログラム上で一緒に使うことはあり
     ません)

   * プラス記号の後ろに一文字、数個の文字、または語を続けたもので、例
     えば "+f", "+rgb"

   * スラッシュ記号の後ろに一文字、数個の文字、または語を続けたもので
     、例えば "/f", "/file"

   These option syntaxes are not supported by "optparse", and they
   never will be.  This is deliberate: the first three are non-
   standard on any environment, and the last only makes sense if
   you're exclusively targeting Windows or certain legacy platforms
   (e.g. VMS, MS-DOS).

オプション引数 (option argument)
   an argument that follows an option, is closely associated with that
   option, and is consumed from the argument list when that option is.
   With "optparse", option arguments may either be in a separate
   argument from their option:

      -f foo
      --file foo

   また、一つの引数中にも入れられます:

      -ffoo
      --file=foo

   Typically, a given option either takes an argument or it doesn't.
   Lots of people want an "optional option arguments" feature, meaning
   that some options will take an argument if they see it, and won't
   if they don't.  This is somewhat controversial, because it makes
   parsing ambiguous: if "-a" takes an optional argument and "-b" is
   another option entirely, how do we interpret "-ab"?  Because of
   this ambiguity, "optparse" does not support this feature.

位置引数 (positional argument)
   他のオプションが解析される、すなわち他のオプションとその引数が解析
   されて引数リストから除去された後に引数リストに置かれているものです
   。

必須のオプション (required option)
   an option that must be supplied on the command-line; note that the
   phrase "required option" is self-contradictory in English.
   "optparse" doesn't prevent you from implementing required options,
   but doesn't give you much help at it either.

例えば、下記のような架空のコマンドラインを考えてみましょう:

   prog -v --report report.txt foo bar

"-v" と "--report" はどちらもオプションです。"--report" オプションが引
数をとるとすれば、"report.txt" はオプションの引数です。"foo" と "bar"
は位置引数になります。


オプションとは何か
------------------

オプションはプログラムの実行を調整したり、カスタマイズしたりするための
補助的な情報を与えるために使います。もっとはっきりいうと、オプションは
あくまでもオプション (省略可能)であるということです。本来、プログラム
はともかくもオプションなしでうまく実行できてしかるべきです。(Unix や
GNU ツールセットのプログラムをランダムにピックアップしてみてください。
オプションを全く指定しなくてもちゃんと動くでしょう？例外は "find",
"tar", "dd" くらいです---これらの例外は、オプション文法が標準的でなく
、インターフェースが混乱を招くと酷評されてきた変種のはみ出しものなので
す)

多くの人が自分のプログラムに「必須のオプション」を持たせたいと考えます
。しかしよく考えてください。必須なら、それは *オプション(省略可能) で
はないのです！* プログラムを正しく動作させるのに絶対的に必要な情報があ
るとすれば、そこには位置引数を割り当てるべきなのです。

良くできたコマンドライン インターフェース設計として、ファイルのコピー
に使われる "cp" ユーティリティのことを考えてみましょう。ファイルのコピ
ーでは、コピー先を指定せずにファイルをコピーするのは無意味な操作ですし
、少なくとも一つのコピー元が必要です。従って、"cp" は引数無しで実行す
ると失敗します。とはいえ、"cp" はオプションを全く必要としない柔軟で便
利なコマンドライン文法を備えています:

   cp SOURCE DEST
   cp SOURCE ... DEST-DIR

まだあります。ほとんどの "cp" の実装では、ファイルモードや変更時刻を変
えずにコピーする、シンボリックリンクの追跡を行わない、すでにあるファイ
ルを上書きする前にユーザに尋ねる、など、ファイルをコピーする方法をいじ
るための一連のオプションを実装しています。しかし、こうしたオプションは
、一つのファイルを別の場所にコピーする、または複数のファイルを別のディ
レクトリにコピーするという、"cp" の中心的な処理を乱すことはないのです
。


位置引数とは何か
----------------

位置引数とは、プログラムを動作させる上で絶対的に必要な情報となる引数で
す。

よいユーザインターフェースとは、絶対に必要だとされるものが可能な限り少
ないものです。プログラムを正しく動作させるために 17 個もの別個の情報が
必要だとしたら、その *方法* はさして問題にはなりません ---ユーザはプロ
グラムを正しく動作させられないうちに諦め、立ち去ってしまうからです。ユ
ーザインターフェースがコマンドラインでも、設定ファイルでも、GUI やその
他の何であっても同じです: 多くの要求をユーザに押し付ければ、ほとんどの
ユーザはただ音をあげてしまうだけなのです。

要するに、ユーザが絶対に提供しなければならない情報だけに制限する ---
そして可能な限りよく練られたデフォルト設定を使うよう試みてください。も
ちろん、プログラムには適度な柔軟性を持たせたいとも望むはずですが、それ
こそがオプションの果たす役割です。繰り返しますが、設定ファイルのエント
リであろうが、GUI でできた「環境設定」ダイアログ上のウィジェットであろ
うが、コマンドラインオプションであろうが関係ありません --- より多くの
オプションを実装すればプログラムはより柔軟性を持ちますが、実装はより難
解になるのです。高すぎる柔軟性はユーザを閉口させ、コードの維持をより難
しくするのです。


チュートリアル
==============

While "optparse" is quite flexible and powerful, it's also
straightforward to use in most cases.  This section covers the code
patterns that are common to any "optparse"-based program.

まず、"OptionParser" クラスを import しておかなければなりません。次に
、プログラムの冒頭で "OptionParser" インスタンスを生成しておきます:

   from optparse import OptionParser
   ...
   parser = OptionParser()

これでオプションを定義できるようになりました。基本的な構文は以下の通り
です:

   parser.add_option(opt_str, ...,
                     attr=value, ...)

Each option has one or more option strings, such as "-f" or "--file",
and several option attributes that tell "optparse" what to expect and
what to do when it encounters that option on the command line.

通常、各オプションには短いオプション文字列と長いオプション文字列があり
ます。例えば:

   parser.add_option("-f", "--file", ...)

オプション文字列は、(ゼロ文字の場合も含め)いくらでも短く、またいくらで
も長くできます。ただしオプション文字列は少なくとも一つなければなりませ
ん。

The option strings passed to "OptionParser.add_option()" are
effectively labels for the option defined by that call.  For brevity,
we will frequently refer to *encountering an option* on the command
line; in reality, "optparse" encounters *option strings* and looks up
options from them.

Once all of your options are defined, instruct "optparse" to parse
your program's command line:

   (options, args) = parser.parse_args()

(お望みなら、 "parse_args()" に自作の引数リストを渡してもかまいません
。とはいえ、実際にはそうした必要はほとんどないでしょう: "optionparser"
はデフォルトで "sys.argv[1:]" を使うからです。)

"parse_args()" は二つの値を返します:

* 全てのオプションに対する値の入ったオブジェクト "options" --- 例えば
  、"--file" が単一の文字列引数をとる場合、"options.file" はユーザが指
  定したファイル名になります。オプションを指定しなかった場合には
  "None" になります

* オプションの解析後に残った位置引数からなるリスト "args"

このチュートリアルの節では、最も重要な四つのオプション属性: "action",
"type", "dest" (destination), "help" についてしか触れません。このうち
最も重要なのは "action" です。


オプション・アクションを理解する
--------------------------------

Actions tell "optparse" what to do when it encounters an option on the
command line.  There is a fixed set of actions hard-coded into
"optparse"; adding new actions is an advanced topic covered in section
Extending optparse.  Most actions tell "optparse" to store a value in
some variable---for example, take a string from the command line and
store it in an attribute of "options".

If you don't specify an option action, "optparse" defaults to "store".


store アクション
----------------

The most common option action is "store", which tells "optparse" to
take the next argument (or the remainder of the current argument),
ensure that it is of the correct type, and store it to your chosen
destination.

例えば:

   parser.add_option("-f", "--file",
                     action="store", type="string", dest="filename")

Now let's make up a fake command line and ask "optparse" to parse it:

   args = ["-f", "foo.txt"]
   (options, args) = parser.parse_args(args)

When "optparse" sees the option string "-f", it consumes the next
argument, "foo.txt", and stores it in "options.filename".  So, after
this call to "parse_args()", "options.filename" is ""foo.txt"".

Some other option types supported by "optparse" are "int" and "float".
Here's an option that expects an integer argument:

   parser.add_option("-n", type="int", dest="num")

このオプションには長い形式のオプション文字列がないため、設定に問題がな
いということに注意してください。また、デフォルトのアクションは "store"
なので、ここでは action を明示的に指定していません。

架空のコマンドラインをもう一つ解析してみましょう。今度は、オプション引
数をオプションの右側にぴったりくっつけて一緒くたにします: "-n42" (一つ
の引数のみ) は "-n 42" (二つの引数からなる) と等価になるので

   (options, args) = parser.parse_args(["-n42"])
   print(options.num)

は "42" を出力します。

If you don't specify a type, "optparse" assumes "string".  Combined
with the fact that the default action is "store", that means our first
example can be a lot shorter:

   parser.add_option("-f", "--file", dest="filename")

If you don't supply a destination, "optparse" figures out a sensible
default from the option strings: if the first long option string is "
--foo-bar", then the default destination is "foo_bar".  If there are
no long option strings, "optparse" looks at the first short option
string: the default destination for "-f" is "f".

"optparse" also includes the built-in "complex" type.  Adding types is
covered in section Extending optparse.


ブール値 (フラグ) オプションの処理
----------------------------------

Flag options---set a variable to true or false when a particular
option is seen---are quite common.  "optparse" supports them with two
separate actions, "store_true" and "store_false".  For example, you
might have a "verbose" flag that is turned on with "-v" and off with
"-q":

   parser.add_option("-v", action="store_true", dest="verbose")
   parser.add_option("-q", action="store_false", dest="verbose")

ここでは二つのオプションに同じ保存先を指定していますが、全く問題ありま
せん。(下記のように、デフォルト値の設定を少し注意深く行わなければなら
ないだけです。)

When "optparse" encounters "-v" on the command line, it sets
"options.verbose" to "True"; when it encounters "-q",
"options.verbose" is set to "False".


その他のアクション
------------------

Some other actions supported by "optparse" are:

""store_const""
   store a constant value, pre-set via "Option.const"

""append""
   オプションの引数を指定のリストに追加します

""count""
   指定のカウンタを 1 増やします

""callback""
   指定の関数を呼び出します

これらのアクションについては、 リファレンスガイド 節および オプション
処理コールバック 節で触れます。


デフォルト値
------------

All of the above examples involve setting some variable (the
"destination") when certain command-line options are seen.  What
happens if those options are never seen?  Since we didn't supply any
defaults, they are all set to "None".  This is usually fine, but
sometimes you want more control.  "optparse" lets you supply a default
value for each destination, which is assigned before the command line
is parsed.

First, consider the verbose/quiet example.  If we want "optparse" to
set "verbose" to "True" unless "-q" is seen, then we can do this:

   parser.add_option("-v", action="store_true", dest="verbose", default=True)
   parser.add_option("-q", action="store_false", dest="verbose")

デフォルトの値は特定のオプションではなく *保存先* に対して適用されます
。また、これら二つのオプションはたまたま同じ保存先を持っているにすぎな
いため、上のコードは下のコードと全く等価になります:

   parser.add_option("-v", action="store_true", dest="verbose")
   parser.add_option("-q", action="store_false", dest="verbose", default=True)

下のような場合を考えてみましょう:

   parser.add_option("-v", action="store_true", dest="verbose", default=False)
   parser.add_option("-q", action="store_false", dest="verbose", default=True)

やはり "verbose" のデフォルト値は "True" になります; 特定の目的変数に
対するデフォルト値として有効なのは、最後に指定した値だからです。

デフォルト値をすっきりと指定するには、 "OptionParser" の
"set_defaults()" メソッドを使います。このメソッドは "parse_args()" を
呼び出す前ならいつでも使えます:

   parser.set_defaults(verbose=True)
   parser.add_option(...)
   (options, args) = parser.parse_args()

前の例と同様、あるオプションの値の保存先に対するデフォルトの値は最後に
指定した値になります。コードを読みやすくするため、デフォルト値を設定す
るときには両方のやり方を混ぜるのではなく、片方だけを使うようにしましょ
う。


ヘルプの生成
------------

"optparse"'s ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces.  All you
have to do is supply a "help" value for each option, and optionally a
short usage message for your whole program.  Here's an OptionParser
populated with user-friendly (documented) options:

   usage = "usage: %prog [options] arg1 arg2"
   parser = OptionParser(usage=usage)
   parser.add_option("-v", "--verbose",
                     action="store_true", dest="verbose", default=True,
                     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", "--filename",
                     metavar="FILE", help="write output to FILE")
   parser.add_option("-m", "--mode",
                     default="intermediate",
                     help="interaction mode: novice, intermediate, "
                          "or expert [default: %default]")

If "optparse" encounters either "-h" or "--help" on the command-line,
or if you just call "parser.print_help()", it prints the following to
standard output:

   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)
     -f FILE, --filename=FILE
                           write output to FILE
     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                           expert [default: intermediate]

(If the help output is triggered by a help option, "optparse" exits
after printing the help text.)

There's a lot going on here to help "optparse" generate the best
possible help message:

* スクリプト自体の利用法を表すメッセージを定義します:

     usage = "usage: %prog [options] arg1 arg2"

  "optparse" expands "%prog" in the usage string to the name of the
  current program, i.e. "os.path.basename(sys.argv[0])".  The expanded
  string is then printed before the detailed option help.

  If you don't supply a usage string, "optparse" uses a bland but
  sensible default: ""Usage: %prog [options]"", which is fine if your
  script doesn't take any positional arguments.

* every option defines a help string, and doesn't worry about line-
  wrapping---"optparse" takes care of wrapping lines and making the
  help output look good.

* オプションが値をとるということは自動的に生成されるヘルプメッセージの
  中で分かります。例えば、"mode" option の場合にはこのようになります:

     -m MODE, --mode=MODE

  Here, "MODE" is called the meta-variable: it stands for the argument
  that the user is expected to supply to "-m"/"--mode".  By default,
  "optparse" converts the destination variable name to uppercase and
  uses that for the meta-variable.  Sometimes, that's not what you
  want---for example, the "--filename" option explicitly sets
  "metavar="FILE"", resulting in this automatically generated option
  description:

     -f FILE, --filename=FILE

  この機能の重要さは、単に表示スペースを節約するといった理由にとどまり
  ません: 上の例では、手作業で書いたヘルプテキストの中でメタ変数として
  "FILE" を使っています。その結果、ユーザに対してやや堅苦しい表現の書
  法 "-f FILE" と、より平易に意味付けを説明した "write output to FILE"
  との間に対応があるというヒントを与えています。これは、エンドユーザに
  とってより明解で便利なヘルプテキストを作成する単純でありながら効果的
  な手法なのです。

* options that have a default value can include "%default" in the help
  string---"optparse" will replace it with "str()" of the option's
  default value.  If an option has no default value (or the default
  value is "None"), "%default" expands to "none".


オプションをグループ化する
~~~~~~~~~~~~~~~~~~~~~~~~~~

たくさんのオプションを扱う場合、オプションをグループ分けするとヘルプ出
力が見やすくなります。 "OptionParser" は、複数のオプションをまとめたオ
プショングループを複数持つことができます。

オプションのグループは、 "OptionGroup" を使って作成します:

class optparse.OptionGroup(parser, title, description=None)

   ここでは:

   * *parser* は、このグループが属する "OptionParser" のインスタンスで
     す

   * *title* はグループのタイトルです

   * *description* はオプションで、グループの長い説明です

"OptionGroup" は ("OptionParser" のように) "OptionContainer" を継承し
ていて、オプションをグループに追加するために "add_option()" メソッドを
利用できます。

全てのオプションを定義したら、 "OptionParser" の "add_option_group()"
メソッドを使ってグループを定義済みのパーサーに追加します。

前のセクションで定義したパーサーに、続けて "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: <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)
     -f FILE, --filename=FILE
                           write output to FILE
     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                           expert [default: intermediate]

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

       -g                  Group option.

さらにサンプルを拡張して、複数のグループを使うようにしてみます:

   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)

   group = OptionGroup(parser, "Debug Options")
   group.add_option("-d", "--debug", action="store_true",
                    help="Print debug information")
   group.add_option("-s", "--sql", action="store_true",
                    help="Print all SQL statements executed")
   group.add_option("-e", action="store_true", help="Print every action done")
   parser.add_option_group(group)

出力結果は次のようになります:

   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)
     -f FILE, --filename=FILE
                           write output to FILE
     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                           [default: intermediate]

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

       -g                  Group option.

     Debug Options:
       -d, --debug         Print debug information
       -s, --sql           Print all SQL statements executed
       -e                  Print every action done

もう1つの、特にオプショングループをプログラムから操作するときに利用で
きるメソッドがあります:

OptionParser.get_option_group(opt_str)

   短いオプション文字列もしくは長いオプション文字列 *opt_str* (例。
   "'-o'" 、 "'--option'") が属する "OptionGroup" を返します。そのよう
   な "OptionGroup" が無い場合は、 "None" を返します。


バージョン番号の出力
--------------------

Similar to the brief usage string, "optparse" can also print a version
string for your program.  You have to supply the string as the
"version" argument to OptionParser:

   parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")

"%prog" is expanded just like it is in "usage".  Apart from that,
"version" can contain anything you like.  When you supply it,
"optparse" automatically adds a "--version" option to your parser. If
it encounters this option on the command line, it expands your
"version" string (by replacing "%prog"), prints it to stdout, and
exits.

例えば、"/usr/bin/foo" という名前のスクリプトなら:

   $ /usr/bin/foo --version
   foo 1.0

以下の2つのメソッドを、"version" 文字列を表示するために利用できます:

OptionParser.print_version(file=None)

   現在のプログラムのバージョン ("self.version") を *file* (デフォルト
   : stdout) へ表示します。 "print_usage()" と同じく、 "self.version"
   の中の全ての "%prog" が現在のプログラム名に置き換えられます。
   "self.version" が空文字列だだったり未定義だったときは何もしません。

OptionParser.get_version()

   "print_version()" と同じですが、バージョン文字列を表示する代わりに
   返します。


How "optparse" handles errors
-----------------------------

There are two broad classes of errors that "optparse" has to worry
about: programmer errors and user errors.  Programmer errors are
usually erroneous calls to "OptionParser.add_option()", e.g. invalid
option strings, unknown option attributes, missing option attributes,
etc.  These are dealt with in the usual way: raise an exception
(either "optparse.OptionError" or "TypeError") and let the program
crash.

Handling user errors is much more important, since they are guaranteed
to happen no matter how stable your code is.  "optparse" can
automatically detect some user errors, such as bad option arguments
(passing "-n 4x" where "-n" takes an integer argument), missing
arguments ("-n" at the end of the command line, where "-n" takes an
argument of any type).  Also, you can call "OptionParser.error()" to
signal an application-defined error condition:

   (options, args) = parser.parse_args()
   ...
   if options.a and options.b:
       parser.error("options -a and -b are mutually exclusive")

In either case, "optparse" handles the error the same way: it prints
the program's usage message and an error message to standard error and
exits with error status 2.

上に挙げた最初の例、すなわち整数を引数にとるオプションにユーザが "4x"
を指定した場合を考えてみましょう:

   $ /usr/bin/foo -n 4x
   Usage: foo [options]

   foo: error: option -n: invalid integer value: '4x'

値を全く指定しない場合には、以下のようになります:

   $ /usr/bin/foo -n
   Usage: foo [options]

   foo: error: -n option requires an argument

"optparse"-generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
"OptionParser.error()" from your application code.

If "optparse"'s default error-handling behaviour does not suit your
needs, you'll need to subclass OptionParser and override its "exit()"
and/or "error()" methods.


全てをつなぎ合わせる
--------------------

Here's what "optparse"-based scripts usually look like:

   from optparse import OptionParser
   ...
   def main():
       usage = "usage: %prog [options] arg"
       parser = OptionParser(usage)
       parser.add_option("-f", "--file", dest="filename",
                         help="read data from FILENAME")
       parser.add_option("-v", "--verbose",
                         action="store_true", dest="verbose")
       parser.add_option("-q", "--quiet",
                         action="store_false", dest="verbose")
       ...
       (options, args) = parser.parse_args()
       if len(args) != 1:
           parser.error("incorrect number of arguments")
       if options.verbose:
           print("reading %s..." % options.filename)
       ...

   if __name__ == "__main__":
       main()


リファレンスガイド
==================


parserを作る
------------

The first step in using "optparse" is to create an OptionParser
instance.

class optparse.OptionParser(...)

   OptionParser のコンストラクタの引数はどれも必須ではありませんが、い
   くつものキーワード引数がオプションとして使えます。これらはキーワー
   ド引数として渡さなければなりません。すなわち、引数が宣言されている
   順番に頼ってはいけません。

   "usage" (デフォルト: ""%prog [options]"")
      The usage summary to print when your program is run incorrectly
      or with a help option.  When "optparse" prints the usage string,
      it expands "%prog" to "os.path.basename(sys.argv[0])" (or to
      "prog" if you passed that keyword argument).  To suppress a
      usage message, pass the special value "optparse.SUPPRESS_USAGE".

   "option_list" (デフォルト: "[]")
      パーザに追加する Option オブジェクトのリストです。 "option_list"
      の中のオプションは "standard_option_list" (OptionParser のサブク
      ラスでセットされる可能性のあるクラス属性) の後に追加されますが、
      バージョンやヘルプのオプションよりは前になります。このオプション
      の使用は推奨されません。パーザを作成した後で、 "add_option()" を
      使って追加してください。

   "option_class" (デフォルト: optparse.Option)
      "add_option()" でパーザにオプションを追加するときに使用されるク
      ラス。

   "version" (デフォルト: "None")
      A version string to print when the user supplies a version
      option. If you supply a true value for "version", "optparse"
      automatically adds a version option with the single option
      string "--version".  The substring "%prog" is expanded the same
      as for "usage".

   "conflict_handler" (デフォルト: ""error"")
      オプション文字列が衝突するようなオプションがパーザに追加されたと
      きにどうするかを指定します。 オプション間の衝突 節を参照して下さ
      い。

   "description" (デフォルト: "None")
      A paragraph of text giving a brief overview of your program.
      "optparse" reformats this paragraph to fit the current terminal
      width and prints it when the user requests help (after "usage",
      but before the list of options).

   "formatter" (デフォルト: 新しい "IndentedHelpFormatter")
      An instance of optparse.HelpFormatter that will be used for
      printing help text.  "optparse" provides two concrete classes
      for this purpose: IndentedHelpFormatter and TitledHelpFormatter.

   "add_help_option" (デフォルト: "True")
      If true, "optparse" will add a help option (with option strings
      "-h" and "--help") to the parser.

   "prog"
      "usage" や "version" の中の "%prog" を展開するときに
      "os.path.basename(sys.argv[0])" の代わりに使われる文字列です。

   "epilog" (デフォルト: "None")
      オプションのヘルプの後に表示されるヘルプテキスト.


パーザへのオプション追加
------------------------

パーザにオプションを加えていくにはいくつか方法があります。推奨するのは
チュートリアル 節で示したような "OptionParser.add_option()" を使う方法
です。 "add_option()" は以下の二つのうちいずれかの方法で呼び出せます:

* ("make_option()" などが返す) "Option" インスタンスを渡します

* "make_option()" に (すなわち "Option" のコンストラクタに) 位置引数と
  キーワード引数の組み合わせを渡して、 "Option" インスタンスを生成させ
  ます

もう一つの方法は、あらかじめ作成しておいた "Option" インスタンスからな
るリストを、以下のようにして "OptionParser" のコンストラクタに渡すとい
うものです:

   option_list = [
       make_option("-f", "--filename",
                   action="store", type="string", dest="filename"),
       make_option("-q", "--quiet",
                   action="store_false", dest="verbose"),
       ]
   parser = OptionParser(option_list=option_list)

("make_option()" is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version
of "optparse" may split Option into several classes, and
"make_option()" will pick the right class to instantiate.  Do not
instantiate Option directly.)


オプションの定義
----------------

各々の "Option" インスタンス、は "-f" や "--file" といった同義のコマン
ドラインオプションからなる集合を表現しています。一つの "Option" には任
意の数のオプションを短い形式でも長い形式でも指定できます。ただし、少な
くとも一つは指定しなければなりません。

正しい方法で "Option" インスタンスを生成するには、 "OptionParser" の
"add_option()" を使います。

OptionParser.add_option(option)
OptionParser.add_option(*opt_str, attr=value, ...)

   短い形式のオプション文字列を一つだけ持つようなオプションを生成する
   には次のようにします:

      parser.add_option("-f", attr=value, ...)

   また、長い形式のオプション文字列を一つだけ持つようなオプションの定
   義は次のようになります:

      parser.add_option("--foo", attr=value, ...)

   The keyword arguments define attributes of the new Option object.
   The most important option attribute is "action", and it largely
   determines which other attributes are relevant or required.  If you
   pass irrelevant option attributes, or fail to pass required ones,
   "optparse" raises an "OptionError" exception explaining your
   mistake.

   An option's *action* determines what "optparse" does when it
   encounters this option on the command-line.  The standard option
   actions hard-coded into "optparse" are:

   ""store""
      オプションの引数を保存します (デフォルトの動作です)

   ""store_const""
      store a constant value, pre-set via "Option.const"

   ""store_true""
      store "True"

   ""store_false""
      store "False"

   ""append""
      オプションの引数を指定のリストに追加します

   ""append_const""
      append a constant value to a list, pre-set via "Option.const"

   ""count""
      指定のカウンタを 1 増やします

   ""callback""
      指定の関数を呼び出します

   ""help""
      全てのオプションとそのドキュメントの入った使用法メッセージを出力
      します

   (アクションを指定しない場合、デフォルトは ""store"" になります。こ
   のアクションでは、 "type" および "dest" オプション属性を指定できま
   す。 標準的なオプション・アクション を参照してください。)

As you can see, most actions involve storing or updating a value
somewhere. "optparse" always creates a special object for this,
conventionally called "options", which is an instance of
"optparse.Values".

class optparse.Values

   An object holding parsed argument names and values as attributes.
   Normally created by calling when calling
   "OptionParser.parse_args()", and can be overridden by a custom
   subclass passed to the *values* argument of
   "OptionParser.parse_args()" (as described in 引数を解析する).

Option arguments (and various other values) are stored as attributes
of this object, according to the "dest" (destination) option
attribute.

例えばこれを呼び出した場合

   parser.parse_args()

one of the first things "optparse" does is create the "options"
object:

   options = Values()

パーザ中で以下のようなオプションが定義されていて

   parser.add_option("-f", "--file", action="store", type="string", dest="filename")

パーズしたコマンドラインに以下のいずれかが入っていた場合:

   -ffoo
   -f foo
   --file=foo
   --file foo

then "optparse", on seeing this option, will do the equivalent of

   options.filename = "foo"

"type" および "dest" オプション属性は "action" と同じくらい重要ですが
、 *全ての* オプションで意味をなすのは "action" だけなのです。


オプション属性
--------------

class optparse.Option

   A single command line argument, with various attributes passed by
   keyword to the constructor. Normally created with
   "OptionParser.add_option()" rather than directly, and can be
   overridden by a custom class via the *option_class* argument to
   "OptionParser".

The following option attributes may be passed as keyword arguments to
"OptionParser.add_option()".  If you pass an option attribute that is
not relevant to a particular option, or fail to pass a required option
attribute, "optparse" raises "OptionError".

Option.action

   (デフォルト: ""store"")

   Determines "optparse"'s behaviour when this option is seen on the
   command line; the available options are documented here.

Option.type

   (デフォルト: ""string"")

   このオプションに与えられる引数の型 (たとえば ""string"" や ""int"")
   です。取りうるオプションについては こちら を参照してください。

Option.dest

   (デフォルト: オプション文字列を使う)

   If the option's action implies writing or modifying a value
   somewhere, this tells "optparse" where to write it: "dest" names an
   attribute of the "options" object that "optparse" builds as it
   parses the command line.

Option.default

   コマンドラインに指定がなかったときにこのオプションの対象に使われる
   値です。 "OptionParser.set_defaults()" も参照してください。

Option.nargs

   (デフォルト: 1)

   How many arguments of type "type" should be consumed when this
   option is seen.  If > 1, "optparse" will store a tuple of values to
   "dest".

Option.const

   定数を格納する動作のための、その定数です。

Option.choices

   ""choice"" 型オプションに対してユーザが選べる選択肢となる文字列のリ
   ストです。

Option.callback

   アクションが ""callback"" であるオプションに対し、このオプションが
   あったときに呼ばれる呼び出し可能オブジェクトです。呼び出し時に渡さ
   れる引数の詳細については、 オプション処理コールバック を参照してく
   ださい。

Option.callback_args
Option.callback_kwargs

   "callback" に渡される標準的な4つのコールバック引数の後ろに追加する
   、位置引数とキーワード引数。

Option.help

   ユーザが "help" オプション("--help" のような)を指定したときに表示さ
   れる、使用可能な全オプションのリストの中のこのオプションに関する説
   明文です。説明文を提供しておかなければ、オプションは説明文なしで表
   示されます。オプションを隠すには特殊な値 "optparse.SUPPRESS_HELP"
   を使います。

Option.metavar

   (デフォルト: オプション文字列を使う)

   説明文を表示する際にオプションの引数の身代わりになるものです。例は
   チュートリアル 節を参照してください。


標準的なオプション・アクション
------------------------------

The various option actions all have slightly different requirements
and effects. Most actions have several relevant option attributes
which you may specify to guide "optparse"'s behaviour; a few have
required attributes, which you must specify for any option using that
action.

* ""store"" [関連: "type", "dest", "nargs", "choices"]

  オプションの後には必ず引数が続きます。引数は "type" に従って値に変換
  されて "dest" に保存されます。 "nargs" > 1 の場合、複数の引数をコマ
  ンドラインから取り出します。引数は全て "type" に従って変換され、
  "dest" にタプルとして保存されます。 標準のオプション型 節を参照して
  ください。

  "choices" を(文字列のリストかタプルで) 指定した場合、型のデフォルト
  値は ""choice"" になります。

  "type" を指定しない場合、デフォルトの値は ""string"" です。

  If "dest" is not supplied, "optparse" derives a destination from the
  first long option string (e.g., "--foo-bar" implies "foo_bar"). If
  there are no long option strings, "optparse" derives a destination
  from the first short option string (e.g., "-f" implies "f").

  以下はプログラム例です:

     parser.add_option("-f")
     parser.add_option("-p", type="float", nargs=3, dest="point")

  とすると、以下のようなコマンドライン

     -f foo.txt -p 1 -3.5 4 -fbar.txt

  "optparse" will set

     options.f = "foo.txt"
     options.point = (1.0, -3.5, 4.0)
     options.f = "bar.txt"

* ""store_const"" [関連: "const"; 関連: "dest"]

  値 "const" を "dest" に保存します。

  以下はプログラム例です:

     parser.add_option("-q", "--quiet",
                       action="store_const", const=0, dest="verbose")
     parser.add_option("-v", "--verbose",
                       action="store_const", const=1, dest="verbose")
     parser.add_option("--noisy",
                       action="store_const", const=2, dest="verbose")

  If "--noisy" is seen, "optparse" will set

     options.verbose = 2

* ""store_true"" [関連: "dest"]

  A special case of ""store_const"" that stores "True" to "dest".

* ""store_false"" [関連: "dest"]

  Like ""store_true"", but stores "False".

  以下はプログラム例です:

     parser.add_option("--clobber", action="store_true", dest="clobber")
     parser.add_option("--no-clobber", action="store_false", dest="clobber")

* ""append"" [関連: "type", "dest", "nargs", "choices"]

  The option must be followed by an argument, which is appended to the
  list in "dest".  If no default value for "dest" is supplied, an
  empty list is automatically created when "optparse" first encounters
  this option on the command-line.  If "nargs" > 1, multiple arguments
  are consumed, and a tuple of length "nargs" is appended to "dest".

  "type" および "dest" のデフォルト値は ""store"" アクションと同じです
  。

  以下はプログラム例です:

     parser.add_option("-t", "--tracks", action="append", type="int")

  If "-t3" is seen on the command-line, "optparse" does the equivalent
  of:

     options.tracks = []
     options.tracks.append(int("3"))

  その後、"--tracks=4" が見つかると以下を実行します:

     options.tracks.append(int("4"))

  "append" アクションは、オプションの現在の値の "append" メソッドを呼
  び出します。これは、どのデフォルト値も "append" メソッドを持っていな
  ければならないことを意味します。また、デフォルト値が空でない場合、オ
  プションの解析結果は、そのデフォルトの要素の後ろにコマンドラインから
  の値が追加されたものになる、ということも意味します:

     >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
     >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
     >>> opts.files
     ['~/.mypkg/defaults', 'overrides.mypkg']

* ""append_const"" [関連: "const"; 関連: "dest"]

  ""store_const"" と同様ですが、 "const" の値は "dest" に追加(append)
  されます。 ""append"" の場合と同じように "dest" のデフォルトは
  "None" ですがこのオプションを最初にみつけた時点で空のリストを自動的
  に生成します。

* ""count"" [関連: "dest"]

  "dest" に保存されている整数値をインクリメントします。 "dest" は (デ
  フォルトの値を指定しない限り) 最初にインクリメントを行う前にゼロに設
  定されます。

  以下はプログラム例です:

     parser.add_option("-v", action="count", dest="verbosity")

  The first time "-v" is seen on the command line, "optparse" does the
  equivalent of:

     options.verbosity = 0
     options.verbosity += 1

  以後、"-v" が見つかるたびに

     options.verbosity += 1

* ""callback"" [必須: "callback"; 関連: "type", "nargs",
  "callback_args", "callback_kwargs"]

  "callback" に指定された関数を次のように呼び出します

     func(option, opt_str, value, parser, *args, **kwargs)

  詳細は、 オプション処理コールバック 節を参照してください。

* ""help""

  現在のオプションパーザ内の全てのオプションに対する完全なヘルプメッセ
  ージを出力します。ヘルプメッセージは "OptionParser" のコンストラクタ
  に渡した "usage"  文字列と、各オプションに渡した "help" 文字列から生
  成します。

  オプションに "help" 文字列が指定されていなくても、オプションはヘルプ
  メッセージ中に列挙されます。オプションを完全に表示させないようにする
  には、特殊な値 "optparse.SUPPRESS_HELP" を使ってください。

  "optparse" automatically adds a "help" option to all OptionParsers,
  so you do not normally need to create one.

  以下はプログラム例です:

     from optparse import OptionParser, SUPPRESS_HELP

     # usually, a help option is added automatically, but that can
     # be suppressed using the add_help_option argument
     parser = OptionParser(add_help_option=False)

     parser.add_option("-h", "--help", action="help")
     parser.add_option("-v", action="store_true", dest="verbose",
                       help="Be moderately verbose")
     parser.add_option("--file", dest="filename",
                       help="Input file to read data from")
     parser.add_option("--secret", help=SUPPRESS_HELP)

  If "optparse" sees either "-h" or "--help" on the command line, it
  will print something like the following help message to stdout
  (assuming "sys.argv[0]" is ""foo.py""):

     Usage: foo.py [options]

     Options:
       -h, --help        Show this help message and exit
       -v                Be moderately verbose
       --file=FILENAME   Input file to read data from

  After printing the help message, "optparse" terminates your process
  with "sys.exit(0)".

* ""version""

  Prints the version number supplied to the OptionParser to stdout and
  exits. The version number is actually formatted and printed by the
  "print_version()" method of OptionParser.  Generally only relevant
  if the "version" argument is supplied to the OptionParser
  constructor.  As with "help" options, you will rarely create
  "version" options, since "optparse" automatically adds them when
  needed.


標準のオプション型
------------------

"optparse" has five built-in option types: ""string"", ""int"",
""choice"", ""float"" and ""complex"".  If you need to add new option
types, see section Extending optparse.

文字列オプションの引数はチェックや変換を一切受けません: コマンドライン
上のテキストは保存先にそのまま保存されます (またはコールバックに渡され
ます)。

整数引数 (""int"" 型) は次のように解析されます:

* 数が "0x" から始まるならば、16進数として読み取られます

* 数が "0" から始まるならば、8進数として読み取られます

* 数が "0b" から始まるならば、2進数として読み取られます

* それ以外の場合、数は10進数として読み取られます

The conversion is done by calling "int()" with the appropriate base
(2, 8, 10, or 16).  If this fails, so will "optparse", although with a
more useful error message.

""float"" および ""complex"" のオプション引数は直接 "float()" や
"complex()" で変換されます。エラーは同様の扱いです。

""choice"" オプションは ""string"" オプションのサブタイプです。
"choices" オプションの属性 (文字列からなるシーケンス) には、利用できる
オプション引数のセットを指定します。 "optparse.check_choice()" はユー
ザの指定したオプション引数とマスタリストを比較して、無効な文字列が指定
された場合には "OptionValueError" を送出します。


引数を解析する
--------------

OptionParser を作成してオプションを追加していく上で大事なポイントは、
"parse_args()" メソッドの呼び出しです。

OptionParser.parse_args(args=None, values=None)

   Parse the command-line options found in *args*.

   The input parameters are

   "args"
      処理する引数のリスト (デフォルト: "sys.argv[1:]")

   "values"
      オプション引数を格納する "Values" のオブジェクト (デフォルト: 新
      しい "Values" のインスタンス) -- 既存のオブジェクトを指定した場
      合、オプションのデフォルトは初期化されません

   and the return value is a pair "(options, args)" where

   "options"
      the same object that was passed in as *values*, or the
      "optparse.Values" instance created by "optparse"

   "args"
      全てのオプションの処理が終わった後で残った位置引数

一番普通の使い方は一切キーワード引数を使わないというものです。
"values" を指定した場合、それは繰り返される "setattr()" の呼び出し (大
雑把に言うと保存される各オプション引数につき一回ずつ) で更新されていき
、 "parse_args()" で返されます。

"parse_args()" が引数リストでエラーに遭遇した場合、 OptionParser の
"error()" メソッドを適切なエンドユーザ向けのエラーメッセージとともに呼
び出します。この呼び出しにより、最終的に終了ステータス 2 (伝統的な
Unix におけるコマンドラインエラーの終了ステータス) でプロセスを終了さ
せることになります。


オプション解析器への問い合わせと操作
------------------------------------

オプションパーザのデフォルトの振る舞いは、ある程度カスタマイズすること
ができます。また、オプションパーザの中を調べることもできます。
"OptionParser" は幾つかのヘルパーメソッドを提供しています:

OptionParser.disable_interspersed_args()

   Set parsing to stop on the first non-option.  For example, if "-a"
   and "-b" are both simple options that take no arguments, "optparse"
   normally accepts this syntax:

      prog -a arg1 -b arg2

   それを次と同じように扱います

      prog -a -b arg1 arg2

   この機能を無効にしたいときは、 "disable_interspersed_args()" メソッ
   ドを呼び出してください。古典的な Unix システムのように、最初のオプ
   ションでない引数を見つけたときにオプションの解析を止めるようになり
   ます。

   別のコマンドを実行するコマンドをプロセッサを作成する際、別のコマン
   ドのオプションと自身のオプションが混ざるのを防ぐために利用すること
   ができます。例えば、各コマンドがそれぞれ異なるオプションのセットを
   持つ場合などに有効です。

OptionParser.enable_interspersed_args()

   オプションで無い最初の引数を見つけてもパースを止めないように設定し
   ます。オプションとコマンド引数の順序が混ざっても良いようになります
   。これはデフォルトの動作です。

OptionParser.get_option(opt_str)

   オプション文字列 *opt_str* に対する "Option" インスタンスを返します
   。該当するオプションがなければ "None" を返します。

OptionParser.has_option(opt_str)

   "OptionParser" に("-q" や "--verbose" のような) オプション
   *opt_str* がある場合、"True" を返します。

OptionParser.remove_option(opt_str)

   "OptionParser" に *opt_str* に対応するオプションがある場合、そのオ
   プションを削除します。該当するオプションに他のオプション文字列が指
   定されていた場合、それらのオプション文字列は全て無効になります。
   *opt_str* がこの "OptionParser" オブジェクトのどのオプションにも属
   さない場合、 "ValueError" を送出します。


オプション間の衝突
------------------

注意が足りないと、衝突するオプションを定義してしまうことがあります:

   parser.add_option("-n", "--dry-run", ...)
   ...
   parser.add_option("-n", "--noisy", ...)

(とりわけ、"OptionParser" から標準的なオプションを備えた自前のサブクラ
スを定義してしまった場合にはよく起きます。)

Every time you add an option, "optparse" checks for conflicts with
existing options.  If it finds any, it invokes the current conflict-
handling mechanism. You can set the conflict-handling mechanism either
in the constructor:

   parser = OptionParser(..., conflict_handler=handler)

個別にも呼び出せます:

   parser.set_conflict_handler(handler)

衝突時の処理をおこなうハンドラ(handler)には、以下のものが利用できます:

   ""error"" (デフォルト)
      オプション間の衝突をプログラム上のエラーとみなし、
      "OptionConflictError" を送出します

   ""resolve""
      オプション間の衝突をインテリジェントに解決します (下記参照)

一例として、衝突をインテリジェントに解決する "OptionParser" を定義し、
衝突を起こすようなオプションを追加してみましょう:

   parser = OptionParser(conflict_handler="resolve")
   parser.add_option("-n", "--dry-run", ..., help="do no harm")
   parser.add_option("-n", "--noisy", ..., help="be noisy")

At this point, "optparse" detects that a previously added option is
already using the "-n" option string.  Since "conflict_handler" is
""resolve"", it resolves the situation by removing "-n" from the
earlier option's list of option strings.  Now "--dry-run" is the only
way for the user to activate that option.  If the user asks for help,
the help message will reflect that:

   Options:
     --dry-run     do no harm
     ...
     -n, --noisy   be noisy

It's possible to whittle away the option strings for a previously
added option until there are none left, and the user has no way of
invoking that option from the command-line.  In that case, "optparse"
removes that option completely, so it doesn't show up in help text or
anywhere else. Carrying on with our existing OptionParser:

   parser.add_option("--dry-run", ..., help="new dry-run option")

At this point, the original "-n"/"--dry-run" option is no longer
accessible, so "optparse" removes it, leaving this help text:

   Options:
     ...
     -n, --noisy   be noisy
     --dry-run     new dry-run option


クリーンアップ
--------------

OptionParser インスタンスはいくつかの循環参照を抱えています。このこと
は Python のガーベジコレクタにとって問題になるわけではありませんが、使
い終わった OptionParser に対して "destroy()" を呼び出すことでこの循環
参照を意図的に断ち切るという方法を選ぶこともできます。この方法は特に長
時間実行するアプリケーションで OptionParser から大きなオブジェクトグラ
フが到達可能になっているような場合に有用です。


その他のメソッド
----------------

OptionParser にはその他にも幾つかの公開されたメソッドがあります:

OptionParser.set_usage(usage)

   上で説明したコンストラクタの "usage" キーワード引数での規則に従った
   使用法の文字列をセットします。 "None" を渡すとデフォルトの使用法文
   字列が使われるようになり、 "optparse.SUPPRESS_USAGE" によって使用法
   メッセージを抑制できます。

OptionParser.print_usage(file=None)

   現在のプログラムの使用法メッセージ ("self.usage") を *file* (デフォ
   ルト: stdout) に表示します。"self.usage" 内にある全ての "%prog" と
   いう文字列は現在のプログラム名に置換されます。"self.usage" が空もし
   くは未定義の時は何もしません。

OptionParser.get_usage()

   "print_usage()" と同じですが、使用法メッセージを表示する代わりに文
   字列として返します。

OptionParser.set_defaults(dest=value, ...)

   幾つかの保存先に対してデフォルト値をまとめてセットします。
   "set_defaults()" を使うのは複数のオプションにデフォルト値をセットす
   る好ましいやり方です。複数のオプションが同じ保存先を共有することが
   あり得るからです。たとえば幾つかの "mode" オプションが全て同じ保存
   先をセットするものだったとすると、どのオプションもデフォルトをセッ
   トすることができ、しかし最後に指定したものだけが有効になります:

      parser.add_option("--advanced", action="store_const",
                        dest="mode", const="advanced",
                        default="novice")    # overridden below
      parser.add_option("--novice", action="store_const",
                        dest="mode", const="novice",
                        default="advanced")  # overrides above setting

   こうした混乱を避けるために "set_defaults()" を使います:

      parser.set_defaults(mode="advanced")
      parser.add_option("--advanced", action="store_const",
                        dest="mode", const="advanced")
      parser.add_option("--novice", action="store_const",
                        dest="mode", const="novice")


オプション処理コールバック
==========================

When "optparse"'s built-in actions and types aren't quite enough for
your needs, you have two choices: extend "optparse" or define a
callback option. Extending "optparse" is more general, but overkill
for a lot of simple cases.  Quite often a simple callback is all you
need.

"callback" オプションの定義は二つのステップからなります:

* ""callback"" アクションを使ってオプション自体を定義する

* コールバックを書く。コールバックは少なくとも後で説明する 4 つの引数
  をとる関数 (またはメソッド) でなければなりません


callbackオプションの定義
------------------------

callback オプションを最も簡単に定義するには、
"OptionParser.add_option()" メソッドを使います。 "action" の他に指定し
なければならない属性は "callback" すなわちコールバックする関数自体です
:

   parser.add_option("-c", action="callback", callback=my_callback)

"callback" is a function (or other callable object), so you must have
already defined "my_callback()" when you create this callback option.
In this simple case, "optparse" doesn't even know if "-c" takes any
arguments, which usually means that the option takes no arguments---
the mere presence of "-c" on the command-line is all it needs to know.
In some circumstances, though, you might want your callback to consume
an arbitrary number of command-line arguments.  This is where writing
callbacks gets tricky; it's covered later in this section.

"optparse" always passes four particular arguments to your callback,
and it will only pass additional arguments if you specify them via
"callback_args" and "callback_kwargs".  Thus, the minimal callback
function signature is:

   def my_callback(option, opt, value, parser):

コールバックの四つの引数については後で説明します。

callback オプションを定義する場合には、他にもいくつかオプション属性を
指定できます:

"type"
   has its usual meaning: as with the ""store"" or ""append"" actions,
   it instructs "optparse" to consume one argument and convert it to
   "type".  Rather than storing the converted value(s) anywhere,
   though, "optparse" passes it to your callback function.

"nargs"
   also has its usual meaning: if it is supplied and > 1, "optparse"
   will consume "nargs" arguments, each of which must be convertible
   to "type".  It then passes a tuple of converted values to your
   callback.

"callback_args"
   その他の位置引数からなるタプルで、コールバックに渡されます

"callback_kwargs"
   その他のキーワード引数からなる辞書で、コールバックに渡されます


コールバック関数はどのように呼び出されるか
------------------------------------------

コールバックは全て以下の形式で呼び出されます:

   func(option, opt_str, value, parser, *args, **kwargs)

ここでは:

"option"
   コールバックを呼び出している "Option" のインスタンスです

"opt_str"
   は、コールバック呼び出しのきっかけとなったコマンドライン上のオプシ
   ョン文字列です。(長い形式のオプションに対する省略形が使われている場
   合、"opt_str" は完全な、正式な形のオプション文字列となります --- 例
   えば、ユーザが "--foobar" の短縮形として "--foo" をコマンドラインに
   入力した時には、"opt_str" は ""--foobar"" となります。)

"value"
   is the argument to this option seen on the command-line.
   "optparse" will only expect an argument if "type" is set; the type
   of "value" will be the type implied by the option's type.  If
   "type" for this option is "None" (no argument expected), then
   "value" will be "None".  If "nargs" > 1, "value" will be a tuple of
   values of the appropriate type.

"parser"
   現在のオプション解析の全てを駆動している "OptionParser" インスタン
   スです。この変数が有用なのは、この値を介してインスタンス属性として
   いくつかの興味深いデータにアクセスできるからです:

   "parser.largs"
      現在放置されている引数、すなわち、すでに消費されたものの、オプシ
      ョンでもオプション引数でもない引数からなるリストです。
      "parser.largs" は自由に変更でき、たとえば引数を追加したりできま
      す (このリストは "args" 、すなわち "parse_args()" の二つ目の戻り
      値になります)

   "parser.rargs"
      現在残っている引数、すなわち、"opt_str" および "value" があれば
      除き、それ以外の引数が残っているリストです。"parser.rargs" は自
      由に変更でき、例えばさらに引数を消費したりできます。

   "parser.values"
      the object where option values are by default stored (an
      instance of optparse.OptionValues).  This lets callbacks use the
      same mechanism as the rest of "optparse" for storing option
      values; you don't need to mess around with globals or closures.
      You can also access or modify the value(s) of any options
      already encountered on the command-line.

"args"
   "callback_args" オプション属性で与えられた任意の位置引数からなるタ
   プルです。

"kwargs"
   "callback_kwargs" オプション属性で与えられた任意のキーワード引数か
   らなるタプルです。


コールバック中で例外を送出する
------------------------------

The callback function should raise "OptionValueError" if there are any
problems with the option or its argument(s).  "optparse" catches this
and terminates the program, printing the error message you supply to
stderr.  Your message should be clear, concise, accurate, and mention
the option at fault. Otherwise, the user will have a hard time
figuring out what they did wrong.


コールバックの例 1: ありふれたコールバック
------------------------------------------

引数をとらず、発見したオプションを単に記録するだけのコールバックオプシ
ョンの例を以下に示します:

   def record_foo_seen(option, opt_str, value, parser):
       parser.values.saw_foo = True

   parser.add_option("--foo", action="callback", callback=record_foo_seen)

もちろん、""store_true"" アクションを使っても実現できます。


コールバックの例 2: オプションの順番をチェックする
--------------------------------------------------

もう少し面白みのある例を示します: この例では、"-b" を発見して、その後
で "-a" がコマンドライン中に現れた場合にはエラーになります。

   def check_order(option, opt_str, value, parser):
       if parser.values.b:
           raise OptionValueError("can't use -a after -b")
       parser.values.a = 1
   ...
   parser.add_option("-a", action="callback", callback=check_order)
   parser.add_option("-b", action="store_true", dest="b")


コールバックの例 3: オプションの順番をチェックする (汎用的)
-----------------------------------------------------------

このコールバック (フラグを立てるが、"-b" が既に指定されていればエラー
になる) を同様の複数のオプションに対して再利用したければ、もう少し作業
する必要があります: エラーメッセージとセットされるフラグを一般化しなけ
ればなりません。

   def check_order(option, opt_str, value, parser):
       if parser.values.b:
           raise OptionValueError("can't use %s after -b" % opt_str)
       setattr(parser.values, option.dest, 1)
   ...
   parser.add_option("-a", action="callback", callback=check_order, dest='a')
   parser.add_option("-b", action="store_true", dest="b")
   parser.add_option("-c", action="callback", callback=check_order, dest='c')


コールバックの例 4: 任意の条件をチェックする
--------------------------------------------

もちろん、単に定義済みのオプションの値を調べるだけにとどまらず、コール
バックには任意の条件を入れられます。例えば、満月でなければ呼び出しては
ならないオプションがあるとしましょう。やらなければならないことはこれだ
けです:

   def check_moon(option, opt_str, value, parser):
       if is_moon_full():
           raise OptionValueError("%s option invalid when moon is full"
                                  % opt_str)
       setattr(parser.values, option.dest, 1)
   ...
   parser.add_option("--foo",
                     action="callback", callback=check_moon, dest="foo")

("is_moon_full()" の定義は読者への課題としましょう。)


コールバックの例5: 固定引数
---------------------------

決まった数の引数をとるようなコールパックオプションを定義するなら、問題
はやや興味深くなってきます。引数をとるようコールバックに指定するのは、
""store"" や ""append"" オプションの定義に似ています。 "type" を定義し
ていれば、そのオプションは引数を受け取ったときに該当する型に変換できな
ければなりません。さらに "nargs" を指定すれば、オプションは "nargs" 個
の引数を受け取ります。

標準の ""store"" アクションをエミュレートする例を以下に示します:

   def store_value(option, opt_str, value, parser):
       setattr(parser.values, option.dest, value)
   ...
   parser.add_option("--foo",
                     action="callback", callback=store_value,
                     type="int", nargs=3, dest="foo")

Note that "optparse" takes care of consuming 3 arguments and
converting them to integers for you; all you have to do is store them.
(Or whatever; obviously you don't need a callback for this example.)


コールバックの例6: 可変個の引数
-------------------------------

Things get hairy when you want an option to take a variable number of
arguments. For this case, you must write a callback, as "optparse"
doesn't provide any built-in capabilities for it.  And you have to
deal with certain intricacies of conventional Unix command-line
parsing that "optparse" normally handles for you.  In particular,
callbacks should implement the conventional rules for bare "--" and
"-" arguments:

* either "--" or "-" can be option arguments

* 裸の "--" (何らかのオプションの引数でない場合): コマンドライン処理を
  停止し、"--" を無視します

* 裸の "-" (何らかのオプションの引数でない場合): コマンドライン処理を
  停止しますが、"-" は残します ("parser.largs" に追加します)

If you want an option that takes a variable number of arguments, there
are several subtle, tricky issues to worry about.  The exact
implementation you choose will be based on which trade-offs you're
willing to make for your application (which is why "optparse" doesn't
support this sort of thing directly).

とはいえ、可変個の引数をもつオプションに対するスタブ (stub、仲介インタ
ーフェース) を以下に示しておきます:

   def vararg_callback(option, opt_str, value, parser):
       assert value is None
       value = []

       def floatable(str):
           try:
               float(str)
               return True
           except ValueError:
               return False

       for arg in parser.rargs:
           # stop on --foo like options
           if arg[:2] == "--" and len(arg) > 2:
               break
           # stop on -a, but not on -3 or -3.0
           if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
               break
           value.append(arg)

       del parser.rargs[:len(value)]
       setattr(parser.values, option.dest, value)

   ...
   parser.add_option("-c", "--callback", dest="vararg_attr",
                     action="callback", callback=vararg_callback)


Extending "optparse"
====================

Since the two major controlling factors in how "optparse" interprets
command-line options are the action and type of each option, the most
likely direction of extension is to add new actions and new types.


新しい型の追加
--------------

To add new types, you need to define your own subclass of "optparse"'s
"Option" class.  This class has a couple of attributes that define
"optparse"'s types: "TYPES" and "TYPE_CHECKER".

Option.TYPES

   "TYPES" は型名のタプルです。新しく作るサブクラスでは、タプル
   "TYPES" を単純に標準のものを利用して新しく定義すると良いでしょう。

Option.TYPE_CHECKER

   "TYPE_CHECKER" は辞書で型名を型チェック関数に対応付けるものです。型
   チェック関数は以下のようなシグネチャを持ちます:

      def check_mytype(option, opt, value)

   ここで "option" は "Option" のインスタンスであり、 "opt" はオプショ
   ン文字列(たとえば "-f")で、 "value" は望みの型としてチェックされ変
   換されるべくコマンドラインで与えられる文字列です。 "check_mytype()"
   は想定されている型 "mytype" のオブジェクトを返さなければなりません
   。型チェック関数から返される値は "OptionParser.parse_args()" で返さ
   れるOptionValues インスタンスに収められるか、またはコールバックに
   "value" パラメータとして渡されます。

   型チェック関数は何か問題に遭遇したら "OptionValueError" を送出しな
   ければなりません。 "OptionValueError" は文字列一つを引数に取り、そ
   れはそのまま "OptionParser" の "error()" メソッドに渡され、そこでプ
   ログラム名と文字列 ""error:"" が前置されてプロセスが終了する前に
   stderr に出力されます。

Here's a silly example that demonstrates adding a ""complex"" option
type to parse Python-style complex numbers on the command line.  (This
is even sillier than it used to be, because "optparse" 1.3 added
built-in support for complex numbers, but never mind.)

最初に必要な import 文を書きます:

   from copy import copy
   from optparse import Option, OptionValueError

まずは型チェック関数を定義しなければなりません。これは後で(これから定
義する Option のサブクラスの "TYPE_CHECKER" クラス属性の中で) 参照され
ることになります:

   def check_complex(option, opt, value):
       try:
           return complex(value)
       except ValueError:
           raise OptionValueError(
               "option %s: invalid complex value: %r" % (opt, value))

最後に Option のサブクラスです:

   class MyOption (Option):
       TYPES = Option.TYPES + ("complex",)
       TYPE_CHECKER = copy(Option.TYPE_CHECKER)
       TYPE_CHECKER["complex"] = check_complex

(If we didn't make a "copy()" of "Option.TYPE_CHECKER", we would end
up modifying the "TYPE_CHECKER" attribute of "optparse"'s Option
class.  This being Python, nothing stops you from doing that except
good manners and common sense.)

That's it!  Now you can write a script that uses the new option type
just like any other "optparse"-based script, except you have to
instruct your OptionParser to use MyOption instead of Option:

   parser = OptionParser(option_class=MyOption)
   parser.add_option("-c", type="complex")

別のやり方として、オプションリストを構築して OptionParser に渡すという
方法もあります。 "add_option()" を上でやったように使わないならば、
OptionParser にどのクラスを使うのか教える必要はありません:

   option_list = [MyOption("-c", action="store", type="complex", dest="c")]
   parser = OptionParser(option_list=option_list)


新しいアクションの追加
----------------------

Adding new actions is a bit trickier, because you have to understand
that "optparse" has a couple of classifications for actions:

"store" アクション
   actions that result in "optparse" storing a value to an attribute
   of the current OptionValues instance; these options require a
   "dest" attribute to be supplied to the Option constructor.

"typed" アクション
   コマンドラインから引数を受け取り、それがある型であることが期待され
   ているアクションです。もう少しはっきり言えば、その型に変換される文
   字列を受け取るものです。この種類のオプションは Option のコンストラ
   クタに "type" 属性を与えることが要求されます。

この分類には重複する部分があります。デフォルトの "store" アクションに
は ""store"", ""store_const"", ""append"", ""count"" などがありますが
、デフォルトの "typed" オプションは ""store"", ""append"",
""callback"" の三つです。

アクションを追加する際に、以下の Option のクラス属性(全て文字列のリス
トです) の中の少なくとも一つに付け加えることでそのアクションを分類する
必要があります:

Option.ACTIONS

   全てのアクションは ACTIONS にリストされていなければなりません。

Option.STORE_ACTIONS

   "store" アクションはここにもリストされます。

Option.TYPED_ACTIONS

   "typed" アクションはここにもリストされます。

Option.ALWAYS_TYPED_ACTIONS

   Actions that always take a type (i.e. whose options always take a
   value) are additionally listed here.  The only effect of this is
   that "optparse" assigns the default type, ""string"", to options
   with no explicit type whose action is listed in
   "ALWAYS_TYPED_ACTIONS".

実際に新しいアクションを実装するには、Option の "take_action()" メソッ
ドをオーバライドしてそのアクションを認識する場合分けを追加しなければな
りません。

例えば、""extend"" アクションというのを追加してみましょう。このアクシ
ョンは標準的な ""append"" アクションと似ていますが、コマンドラインから
一つだけ値を読み取って既存のリストに追加するのではなく、複数の値をコン
マ区切りの文字列として読み取ってそれらで既存のリストを拡張します。すな
わち、もし "--names" が ""string"" 型の ""extend"" オプションだとする
と、次のコマンドライン

   --names=foo,bar --names blah --names ding,dong

の結果は次のリストになります

   ["foo", "bar", "blah", "ding", "dong"]

再び Option のサブクラスを定義します:

   class MyOption(Option):

       ACTIONS = Option.ACTIONS + ("extend",)
       STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
       TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
       ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

       def take_action(self, action, dest, opt, value, values, parser):
           if action == "extend":
               lvalue = value.split(",")
               values.ensure_value(dest, []).extend(lvalue)
           else:
               Option.take_action(
                   self, action, dest, opt, value, values, parser)

注意すべきは次のようなところです:

* ""extend"" はコマンドラインの値を予期していると同時にその値をどこか
  に格納しますので、 "STORE_ACTIONS" と "TYPED_ACTIONS" の両方に入りま
  す。

* to ensure that "optparse" assigns the default type of ""string"" to
  ""extend"" actions, we put the ""extend"" action in
  "ALWAYS_TYPED_ACTIONS" as well.

* "MyOption.take_action()" implements just this one new action, and
  passes control back to "Option.take_action()" for the standard
  "optparse" actions.

* "values" は optparse_parser.Values クラスのインスタンスであり、非常
  に有用な "ensure_value()" メソッドを提供しています。
  "ensure_value()" は本質的に安全弁付きの "getattr()" です。次のように
  呼び出します

     values.ensure_value(attr, value)

  "values" に "attr" 属性が無いか "None" だった場合に、
  "ensure_value()" は最初に "value" をセットし、それから "value" を返
  します。この振る舞いは ""extend"", ""append"", ""count"" のように、
  データを変数に集積し、またその変数がある型 (最初の二つはリスト、最後
  のは整数) であると期待されるアクションを作るのにとても使い易いもので
  す。 "ensure_value()" を使えば、作ったアクションを使うスクリプトはオ
  プションに保存先にデフォルト値をセットすることに煩わされずに済みます
  。デフォルトを "None" にしておけば "ensure_value()" がそれが必要にな
  ったときに適当な値を返してくれます。


例外
====

exception optparse.OptionError

   Raised if an "Option" instance is created with invalid or
   inconsistent arguments.

exception optparse.OptionConflictError

   Raised if conflicting options are added to an "OptionParser".

exception optparse.OptionValueError

   Raised if an invalid option value is encountered on the command
   line.

exception optparse.BadOptionError

   Raised if an invalid option is passed on the command line.

exception optparse.AmbiguousOptionError

   Raised if an ambiguous option is passed on the command line.
