"argparse" --- Parser for command-line options, arguments and sub-commands
**************************************************************************

バージョン 3.2 で追加.

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

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


チュートリアル
^^^^^^^^^^^^^^

このページは API のリファレンス情報が記載しています。argparse チュート
リアル では、コマンドラインの解析についてより優しく説明しています。

The "argparse" module makes it easy to write user-friendly command-
line interfaces. The program defines what arguments it requires, and
"argparse" will figure out how to parse those out of "sys.argv".  The
"argparse" module also automatically generates help and usage
messages.  The module will also issue errors when users give the
program invalid arguments.


Core Functionality
==================

The "argparse" module's support for command-line interfaces is built
around an instance of "argparse.ArgumentParser".  It is a container
for argument specifications and has options that apply the parser as
whole:

   parser = argparse.ArgumentParser(
                       prog='ProgramName',
                       description='What the program does',
                       epilog='Text at the bottom of help')

"ArgumentParser.add_argument()" メソッドは各引数の仕様をパーサーに付属
させます。このメソッドは位置引数、値を受け取るオプション、機能のオン／
オフを切り替えるフラグをサポートします:

   parser.add_argument('filename')           # positional argument
   parser.add_argument('-c', '--count')      # option that takes a value
   parser.add_argument('-v', '--verbose',
                       action='store_true')  # on/off flag

"ArgumentParser.parse_args()" メソッドはパーサーを実行し、抽出したデー
タを "argparse.Namespace" オブジェクト内に配置します:

   args = parser.parse_args()
   print(args.filename, args.count, args.verbose)


Quick Links for add_argument()
==============================

+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| Name                   | Description                                                 | Values                                                                                                                     |
|========================|=============================================================|============================================================================================================================|
| action                 | Specify how an argument should be handled                   | "'store'", "'store_const'", "'store_true'", "'append'", "'append_const'", "'count'", "'help'", "'version'"                 |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| choices                | Limit values to a specific set of choices                   | "['foo', 'bar']", "range(1, 10)", or "Container" instance                                                                  |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| const                  | Store a constant value                                      |                                                                                                                            |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| default                | Default value used when an argument is not provided         | Defaults to "None"                                                                                                         |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| dest                   | Specify the attribute name used in the result namespace     |                                                                                                                            |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| help                   | Help message for an argument                                |                                                                                                                            |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| metavar                | Alternate display name for the argument as shown in help    |                                                                                                                            |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| nargs                  | Number of times the argument can be used                    | "int", "'?'", "'*'", or "'+'"                                                                                              |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| required               | Indicate whether an argument is required or optional        | "True" or "False"                                                                                                          |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+
| type                   | Automatically convert an argument to the given type         | "int", "float", "argparse.FileType('w')", or callable function                                                             |
+------------------------+-------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------+


Example
=======

The following code is a Python program that takes a list of integers
and produces either the sum or the max:

   import argparse

   parser = argparse.ArgumentParser(description='Process some integers.')
   parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
   parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')

   args = parser.parse_args()
   print(args.accumulate(args.integers))

Assuming the above Python code is saved into a file called "prog.py",
it can be run at the command line and it provides useful help
messages:

   $ python prog.py -h
   usage: prog.py [-h] [--sum] N [N ...]

   Process some integers.

   positional arguments:
    N           an integer for the accumulator

   options:
    -h, --help  show this help message and exit
    --sum       sum the integers (default: find the max)

When run with the appropriate arguments, it prints either the sum or
the max of the command-line integers:

   $ python prog.py 1 2 3 4
   4

   $ python prog.py 1 2 3 4 --sum
   10

If invalid arguments are passed in, an error will be displayed:

   $ python prog.py a b c
   usage: prog.py [-h] [--sum] N [N ...]
   prog.py: error: argument N: invalid int value: 'a'

The following sections walk you through this example.


Creating a parser
-----------------

The first step in using the "argparse" is creating an "ArgumentParser"
object:

   >>> parser = argparse.ArgumentParser(description='Process some integers.')

The "ArgumentParser" object will hold all the information necessary to
parse the command line into Python data types.


Adding arguments
----------------

Filling an "ArgumentParser" with information about program arguments
is done by making calls to the "add_argument()" method. Generally,
these calls tell the "ArgumentParser" how to take the strings on the
command line and turn them into objects.  This information is stored
and used when "parse_args()" is called. For example:

   >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
   ...                     help='an integer for the accumulator')
   >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
   ...                     const=sum, default=max,
   ...                     help='sum the integers (default: find the max)')

Later, calling "parse_args()" will return an object with two
attributes, "integers" and "accumulate".  The "integers" attribute
will be a list of one or more integers, and the "accumulate" attribute
will be either the "sum()" function, if "--sum" was specified at the
command line, or the "max()" function if it was not.


Parsing arguments
-----------------

"ArgumentParser" parses arguments through the "parse_args()" method.
This will inspect the command line, convert each argument to the
appropriate type and then invoke the appropriate action. In most
cases, this means a simple "Namespace" object will be built up from
attributes parsed out of the command line:

   >>> parser.parse_args(['--sum', '7', '-1', '42'])
   Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

In a script, "parse_args()" will typically be called with no
arguments, and the "ArgumentParser" will automatically determine the
command-line arguments from "sys.argv".


ArgumentParser オブジェクト
===========================

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)

   新しい "ArgumentParser" オブジェクトを生成します。すべての引数はキ
   ーワード引数として渡すべきです。各引数についてはあとで詳しく説明し
   ますが、簡単に言うと:

   * prog - The name of the program (default:
     "os.path.basename(sys.argv[0])")

   * usage - プログラムの利用方法を記述する文字列 (デフォルト: パーサ
     ーに追加された引数から生成されます)

   * description - 引数のヘルプの前に表示されるテキスト (デフォルトは
     テキストなしです)

   * epilog - 引数のヘルプの後に表示されるテキスト (デフォルトはテキス
     トなしです)

   * parents - "ArgumentParser" オブジェクトのリストで、このオブジェク
     トの引数が追加されます

   * formatter_class - ヘルプ出力をカスタマイズするためのクラス

   * prefix_chars - オプションの引数の prefix になる文字集合 (デフォル
     ト: '-')

   * fromfile_prefix_chars - 追加の引数を読み込むファイルの prefix に
     なる文字集合 (デフォルト: "None")

   * argument_default - 引数のグローバルなデフォルト値 (デフォルト:
     "None")

   * conflict_handler - 衝突するオプションを解決する方法 (通常は不要)

   * add_help - "-h/--help" オプションをパーサーに追加する (デフォルト
     : "True")

   * allow_abbrev - Allows long options to be abbreviated if the
     abbreviation is unambiguous. (default: "True")

   * exit_on_error - Determines whether or not ArgumentParser exits
     with error info when an error occurs. (default: "True")

   バージョン 3.5 で変更: *allow_abbrev* 引数が追加されました。

   バージョン 3.8 で変更: 以前のバージョンでは、 *allow_abbrev* は、
   "-vv" が "-v -v" と等価になるような、短いフラグのグループ化を無効に
   していました。

   バージョン 3.9 で変更: *exit_on_error* 引数が追加されました。

以下の節では各オプションの利用方法を説明します。


"prog"
------

By default, "ArgumentParser" objects use "sys.argv[0]" to determine
how to display the name of the program in help messages.  This default
is almost always desirable because it will make the help messages
match how the program was invoked on the command line.  For example,
consider a file named "myprogram.py" with the following code:

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument('--foo', help='foo help')
   args = parser.parse_args()

The help for this program will display "myprogram.py" as the program
name (regardless of where the program was invoked from):

   $ python myprogram.py --help
   usage: myprogram.py [-h] [--foo FOO]

   options:
    -h, --help  show this help message and exit
    --foo FOO   foo help
   $ cd ..
   $ python subdir/myprogram.py --help
   usage: myprogram.py [-h] [--foo FOO]

   options:
    -h, --help  show this help message and exit
    --foo FOO   foo help

To change this default behavior, another value can be supplied using
the "prog=" argument to "ArgumentParser":

   >>> parser = argparse.ArgumentParser(prog='myprogram')
   >>> parser.print_help()
   usage: myprogram [-h]

   options:
    -h, --help  show this help message and exit

Note that the program name, whether determined from "sys.argv[0]" or
from the "prog=" argument, is available to help messages using the
"%(prog)s" format specifier.

   >>> parser = argparse.ArgumentParser(prog='myprogram')
   >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
   >>> parser.print_help()
   usage: myprogram [-h] [--foo FOO]

   options:
    -h, --help  show this help message and exit
    --foo FOO   foo of the myprogram program


usage
-----

By default, "ArgumentParser" calculates the usage message from the
arguments it contains:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('--foo', nargs='?', help='foo help')
   >>> parser.add_argument('bar', nargs='+', help='bar help')
   >>> parser.print_help()
   usage: PROG [-h] [--foo [FOO]] bar [bar ...]

   positional arguments:
    bar          bar help

   options:
    -h, --help   show this help message and exit
    --foo [FOO]  foo help

The default message can be overridden with the "usage=" keyword
argument:

   >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
   >>> parser.add_argument('--foo', nargs='?', help='foo help')
   >>> parser.add_argument('bar', nargs='+', help='bar help')
   >>> parser.print_help()
   usage: PROG [options]

   positional arguments:
    bar          bar help

   options:
    -h, --help   show this help message and exit
    --foo [FOO]  foo help

"%(prog)s" フォーマット指定子を、使用法メッセージ内でプログラム名とし
て利用できます。


description
-----------

Most calls to the "ArgumentParser" constructor will use the
"description=" keyword argument.  This argument gives a brief
description of what the program does and how it works.  In help
messages, the description is displayed between the command-line usage
string and the help messages for the various arguments:

   >>> parser = argparse.ArgumentParser(description='A foo that bars')
   >>> parser.print_help()
   usage: argparse.py [-h]

   A foo that bars

   options:
    -h, --help  show this help message and exit

デフォルトでは、説明は与えられたスペースに合わせて折り返されます。この
挙動を変更するには、formatter_class 引数を参照してください。


epilog
------

いくつかのプログラムは、プログラムについての追加の説明を引数の説明の後
に表示します。このテキストは "ArgumentParser" の "epilog=" 引数に指定
できます:

   >>> parser = argparse.ArgumentParser(
   ...     description='A foo that bars',
   ...     epilog="And that's how you'd foo a bar")
   >>> parser.print_help()
   usage: argparse.py [-h]

   A foo that bars

   options:
    -h, --help  show this help message and exit

   And that's how you'd foo a bar

description 引数と同じく、"epilog=" テキストもデフォルトで折り返され、
"ArgumentParser" の formatter_class 引数で動作を調整できます。


parents
-------

ときどき、いくつかのパーサーが共通の引数セットを共有することがあります
。それらの引数を繰り返し定義する代わりに、すべての共通引数を持ったパー
サーを "ArgumentParser" の "parents=" 引数に渡すことができます。
"parents=" 引数は "ArgumentParser" オブジェクトのリストを受け取り、す
べての位置アクションとオプションのアクションをそれらから集め、そのアク
ションを構築中の "ArgumentParser" オブジェクトに追加します:

   >>> parent_parser = argparse.ArgumentParser(add_help=False)
   >>> parent_parser.add_argument('--parent', type=int)

   >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
   >>> foo_parser.add_argument('foo')
   >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
   Namespace(foo='XXX', parent=2)

   >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
   >>> bar_parser.add_argument('--bar')
   >>> bar_parser.parse_args(['--bar', 'YYY'])
   Namespace(bar='YYY', parent=None)

一番親になるパーサーに "add_help=False" を指定していることに注目してく
ださい。こうしないと、"ArgumentParser" は2つの "-h/--help" オプション
を与えられる (1つは親から、もうひとつは子から) ことになり、エラーを発
生します。

注釈:

  "parents=" に渡す前にパーサーを完全に初期化する必要があります。子パ
  ーサーを作成してから親パーサーを変更した場合、その変更は子パーサーに
  反映されません。


formatter_class
---------------

"ArgumentParser" オブジェクトは代わりのフォーマットクラスを指定するこ
とでヘルプのフォーマットをカスタマイズできます。現在、4つのフォーマッ
トクラスがあります:

class argparse.RawDescriptionHelpFormatter
class argparse.RawTextHelpFormatter
class argparse.ArgumentDefaultsHelpFormatter
class argparse.MetavarTypeHelpFormatter

"RawDescriptionHelpFormatter" と "RawTextHelpFormatter" はどのようにテ
キストの説明を表示するかを指定できます。デフォルトでは
"ArgumentParser" オブジェクトはコマンドラインヘルプの中の description
と epilog を折り返して表示します:

   >>> parser = argparse.ArgumentParser(
   ...     prog='PROG',
   ...     description='''this description
   ...         was indented weird
   ...             but that is okay''',
   ...     epilog='''
   ...             likewise for this epilog whose whitespace will
   ...         be cleaned up and whose words will be wrapped
   ...         across a couple lines''')
   >>> parser.print_help()
   usage: PROG [-h]

   this description was indented weird but that is okay

   options:
    -h, --help  show this help message and exit

   likewise for this epilog whose whitespace will be cleaned up and whose words
   will be wrapped across a couple lines

"formatter_class=" に "RawDescriptionHelpFormatter" を渡した場合、
description と epilog は整形済みとされ改行されません:

   >>> parser = argparse.ArgumentParser(
   ...     prog='PROG',
   ...     formatter_class=argparse.RawDescriptionHelpFormatter,
   ...     description=textwrap.dedent('''\
   ...         Please do not mess up this text!
   ...         --------------------------------
   ...             I have indented it
   ...             exactly the way
   ...             I want it
   ...         '''))
   >>> parser.print_help()
   usage: PROG [-h]

   Please do not mess up this text!
   --------------------------------
      I have indented it
      exactly the way
      I want it

   options:
    -h, --help  show this help message and exit

"RawTextHelpFormatter" maintains whitespace for all sorts of help
text, including argument descriptions. However, multiple new lines are
replaced with one. If you wish to preserve multiple blank lines, add
spaces between the newlines.

"ArgumentDefaultsHelpFormatter" は各引数のデフォルト値を自動的にヘルプ
に追加します:

   >>> parser = argparse.ArgumentParser(
   ...     prog='PROG',
   ...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
   >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
   >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
   >>> parser.print_help()
   usage: PROG [-h] [--foo FOO] [bar ...]

   positional arguments:
    bar         BAR! (default: [1, 2, 3])

   options:
    -h, --help  show this help message and exit
    --foo FOO   FOO! (default: 42)

"MetavarTypeHelpFormatter" は、各引数の値の表示名に type 引数の値を使
用します (通常は dest の値が使用されます):

   >>> parser = argparse.ArgumentParser(
   ...     prog='PROG',
   ...     formatter_class=argparse.MetavarTypeHelpFormatter)
   >>> parser.add_argument('--foo', type=int)
   >>> parser.add_argument('bar', type=float)
   >>> parser.print_help()
   usage: PROG [-h] [--foo int] float

   positional arguments:
     float

   options:
     -h, --help  show this help message and exit
     --foo int


prefix_chars
------------

Most command-line options will use "-" as the prefix, e.g. "-f/--foo".
Parsers that need to support different or additional prefix
characters, e.g. for options like "+f" or "/foo", may specify them
using the "prefix_chars=" argument to the ArgumentParser constructor:

   >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
   >>> parser.add_argument('+f')
   >>> parser.add_argument('++bar')
   >>> parser.parse_args('+f X ++bar Y'.split())
   Namespace(bar='Y', f='X')

"prefix_chars=" 引数のデフォルトは "'-'" です。"-" を含まない文字セッ
トを指定すると、"-f/--foo" オプションが使用できなくなります。


fromfile_prefix_chars
---------------------

ときどき、非常に長い引数リストを扱う場合に、その引数リストを毎回コマン
ドラインにタイプする代わりにファイルに置いておきたい場合があります。
"ArgumentParser" のコンストラクターに "fromfile_prefix_chars=" 引数が
渡された場合、指定された文字のいずれかで始まる引数はファイルとして扱わ
れ、そのファイルに含まれる引数リストに置換されます。例えば:

   >>> with open('args.txt', 'w') as fp:
   ...     fp.write('-f\nbar')
   >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
   >>> parser.add_argument('-f')
   >>> parser.parse_args(['-f', 'foo', '@args.txt'])
   Namespace(f='bar')

ファイルから読み込まれる引数は、デフォルトでは1行に1つ (ただし、
"convert_arg_line_to_args()" も参照してください) で、コマンドライン上
でファイルを参照する引数があった場所にその引数があったものとして扱われ
ます。このため、上の例では、"['-f', 'foo', '@args.txt']" は "['-f',
'foo', '-f', 'bar']" と等価になります。

"fromfile_prefix_chars=" 引数のデフォルト値は "None" で、引数がファイ
ル参照として扱われることがないことを意味しています。


argument_default
----------------

一般的には、引数のデフォルト値は "add_argument()" メソッドにデフォルト
値を渡すか、"set_defaults()" メソッドに名前と値のペアを渡すことで指定
します。しかしまれに、1つのパーサー全体に適用されるデフォルト引数が便
利なことがあります。これを行うには、 "ArgumentParser" に
"argument_default=" キーワード引数を渡します。例えば、全体で
"parse_args()" メソッド呼び出しの属性の生成を抑制するには、
"argument_default=SUPPRESS" を指定します:

   >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
   >>> parser.add_argument('--foo')
   >>> parser.add_argument('bar', nargs='?')
   >>> parser.parse_args(['--foo', '1', 'BAR'])
   Namespace(bar='BAR', foo='1')
   >>> parser.parse_args([])
   Namespace()


allow_abbrev
------------

通常、"ArgumentParser" の "parse_args()" に引数のリストを渡すとき、長
いオプションは 短縮しても認識されます。

この機能は、"allow_abbrev" に "False" を指定することで無効にできます:

   >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
   >>> parser.add_argument('--foobar', action='store_true')
   >>> parser.add_argument('--foonley', action='store_false')
   >>> parser.parse_args(['--foon'])
   usage: PROG [-h] [--foobar] [--foonley]
   PROG: error: unrecognized arguments: --foon

バージョン 3.5 で追加.


conflict_handler
----------------

"ArgumentParser" オブジェクトは同じオプション文字列に対して複数のアク
ションを許可していません。 デフォルトでは、"ArgumentParser" オブジェク
トは、すでに利用されているオプション文字列を使って新しい引数をつくろう
としたときに例外を送出します:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-f', '--foo', help='old foo help')
   >>> parser.add_argument('--foo', help='new foo help')
   Traceback (most recent call last):
    ..
   ArgumentError: argument --foo: conflicting option string(s): --foo

ときどき (例えば parents を利用する場合など)、古い引数を同じオプション
文字列で上書きするほうが便利な場合があります。この動作をするには、
"ArgumentParser" の "conflict_handler=" 引数に "'resolve'" を渡します:

   >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
   >>> parser.add_argument('-f', '--foo', help='old foo help')
   >>> parser.add_argument('--foo', help='new foo help')
   >>> parser.print_help()
   usage: PROG [-h] [-f FOO] [--foo FOO]

   options:
    -h, --help  show this help message and exit
    -f FOO      old foo help
    --foo FOO   new foo help

"ArgumentParser" オブジェクトは、すべてのオプション文字列が上書きされ
た場合にだけアクションを削除することに注目してください。上の例では、 "
--foo" オプション文字列だけが上書きされているので、古い "-f/--foo" ア
クションは "-f" アクションとして残っています。


add_help
--------

By default, ArgumentParser objects add an option which simply displays
the parser's help message. For example, consider a file named
"myprogram.py" containing the following code:

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument('--foo', help='foo help')
   args = parser.parse_args()

If "-h" or "--help" is supplied at the command line, the
ArgumentParser help will be printed:

   $ python myprogram.py --help
   usage: myprogram.py [-h] [--foo FOO]

   options:
    -h, --help  show this help message and exit
    --foo FOO   foo help

必要に応じて、この help オプションを無効にする場合があります。これは
"ArgumentParser" の "add_help=" 引数に "False" を渡すことで可能です:

   >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
   >>> parser.add_argument('--foo', help='foo help')
   >>> parser.print_help()
   usage: PROG [--foo FOO]

   options:
    --foo FOO  foo help

ヘルプオプションは通常 "-h/--help" です。例外は "prefix_chars=" が指定
されてその中に "-" が無かった場合で、その場合は "-h" と "--help" は有
効なオプションではありません。この場合、"prefix_chars" の最初の文字が
ヘルプオプションの接頭辞として利用されます:

   >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
   >>> parser.print_help()
   usage: PROG [+h]

   options:
     +h, ++help  show this help message and exit


exit_on_error
-------------

Normally, when you pass an invalid argument list to the "parse_args()"
method of an "ArgumentParser", it will exit with error info.

もしエラーを例外としてプログラム内でキャッチしたい場合は、
"exit_on_error" を "False" に設定してください:

   >>> parser = argparse.ArgumentParser(exit_on_error=False)
   >>> parser.add_argument('--integers', type=int)
   _StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)
   >>> try:
   ...     parser.parse_args('--integers a'.split())
   ... except argparse.ArgumentError:
   ...     print('Catching an argumentError')
   ...
   Catching an argumentError

バージョン 3.9 で追加.


add_argument() メソッド
=======================

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

   1つのコマンドライン引数がどう解析されるかを定義します。各引数につい
   ての詳細は後述しますが、簡単に言うと:

   * name or flags - Either a name or a list of option strings, e.g.
     "foo" or "-f, --foo".

   * action - コマンドラインにこの引数があったときのアクション。

   * nargs - 受け取るべきコマンドライン引数の数。

   * const - 一部の action と nargs の組み合わせで利用される定数。

   * default - コマンドラインに対応する引数が存在せず、さらに
     namespace オブジェクトにも存在しない場合に利用される値。

   * type - コマンドライン引数が変換されるべき型。

   * choices - 引数として許される値のシーケンス。

   * required - コマンドラインオプションが省略可能かどうか (オプション
     引数のみ)。

   * help - 引数が何なのかを示す簡潔な説明。

   * metavar - 使用法メッセージの中で使われる引数の名前。

   * dest - "parse_args()" が返すオブジェクトに追加される属性名。

以下の節では各オプションの利用方法を説明します。


name または flags
-----------------

"add_argument()" メソッドは、指定されている引数が "-f" や "--foo" のよ
うなオプション引数なのか、ファイル名リストなどの位置引数なのかを知る必
要があります。 そのため、 "add_argument()" に初めに渡される引数は、一
連のフラグか、単一の引数名のどちらかになります。

たとえば、オプション引数は次のように作成します:

   >>> parser.add_argument('-f', '--foo')

一方、位置引数は次のように作成します:

   >>> parser.add_argument('bar')

"parse_args()" が呼ばれたとき、オプション引数は接頭辞 "-" により識別さ
れ、それ以外の引数は位置引数として扱われます:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-f', '--foo')
   >>> parser.add_argument('bar')
   >>> parser.parse_args(['BAR'])
   Namespace(bar='BAR', foo=None)
   >>> parser.parse_args(['BAR', '--foo', 'FOO'])
   Namespace(bar='BAR', foo='FOO')
   >>> parser.parse_args(['--foo', 'FOO'])
   usage: PROG [-h] [-f FOO] bar
   PROG: error: the following arguments are required: bar


action
------

"ArgumentParser" オブジェクトはコマンドライン引数にアクションを割り当
てます。このアクションは、割り当てられたコマンドライン引数に関してどん
な処理でもできますが、ほとんどのアクションは単に "parse_args()" が返す
オブジェクトに属性を追加するだけです。"action" キーワード引数は、コマ
ンドライン引数がどう処理されるかを指定します。提供されているアクション
は:

* "'store'" - This just stores the argument's value.  This is the
  default action. For example:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo')
     >>> parser.parse_args('--foo 1'.split())
     Namespace(foo='1')

* "'store_const'" - このアクションは const キーワード引数で指定された
  値を格納します。const キーワード引数のデフォルト値は "None" であるこ
  とに注意してください。"'store_const'" アクションは、何かの種類のフラ
  グを指定するオプション引数によく使われます。例えば:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', action='store_const', const=42)
     >>> parser.parse_args(['--foo'])
     Namespace(foo=42)

* "'store_true'" and "'store_false'" - These are special cases of
  "'store_const'" used for storing the values "True" and "False"
  respectively.  In addition, they create default values of "False"
  and "True" respectively.  For example:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', action='store_true')
     >>> parser.add_argument('--bar', action='store_false')
     >>> parser.add_argument('--baz', action='store_false')
     >>> parser.parse_args('--foo --bar'.split())
     Namespace(foo=True, bar=False, baz=True)

* "'append'" - このアクションはリストを格納し、それぞれの引数として与
  えられた値をリストに追加します。これは複数回指定可能なオプション引数
  に対して有用です。デフォルト値が空でない場合、デフォルト値は常にパー
  スされたリストに含まれ、コマンドラインで指定した値はデフォルト値の後
  に追加されます。使用例:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', action='append')
     >>> parser.parse_args('--foo 1 --foo 2'.split())
     Namespace(foo=['1', '2'])

* "'append_const'" - このアクションはリストを格納して、const キーワー
  ド引数に与えられた値をそのリストに追加します。const キーワード引数の
  デフォルト値は "None" であることに注意してください。"'append_const'"
  アクションは、定数を同じリストに複数回格納する場合に便利です。例えば
  :

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
     >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
     >>> parser.parse_args('--str --int'.split())
     Namespace(types=[<class 'str'>, <class 'int'>])

* "'count'" - このアクションはキーワード引数の数を数えます。例えば、
  verboseレベルを上げるのに役立ちます:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--verbose', '-v', action='count', default=0)
     >>> parser.parse_args(['-vvv'])
     Namespace(verbose=3)

  *default* は明示的に *0* と指定されない場合は "None" であることに注
  意してください。

* "'help'" - このアクションは現在のパーサー中のすべてのオプションのヘ
  ルプメッセージを表示し、終了します。出力の生成方法の詳細については
  "ArgumentParser" を参照してください。

* "'version'" - このアクションは "add_argument()" の呼び出しに
  "version=" キーワード引数を期待します。指定されたときはバージョン情
  報を表示して終了します:

     >>> import argparse
     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
     >>> parser.parse_args(['--version'])
     PROG 2.0

* "'extend'" - This stores a list, and extends each argument value to
  the list. Example usage:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
     >>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
     Namespace(foo=['f1', 'f2', 'f3', 'f4'])

  バージョン 3.8 で追加.

You may also specify an arbitrary action by passing an Action subclass
or other object that implements the same interface. The
"BooleanOptionalAction" is available in "argparse" and adds support
for boolean actions such as "--foo" and "--no-foo":

   >>> import argparse
   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
   >>> parser.parse_args(['--no-foo'])
   Namespace(foo=False)

バージョン 3.9 で追加.

The recommended way to create a custom action is to extend "Action",
overriding the "__call__" method and optionally the "__init__" and
"format_usage" methods.

カスタムアクションの例です:

   >>> class FooAction(argparse.Action):
   ...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
   ...         if nargs is not None:
   ...             raise ValueError("nargs not allowed")
   ...         super().__init__(option_strings, dest, **kwargs)
   ...     def __call__(self, parser, namespace, values, option_string=None):
   ...         print('%r %r %r' % (namespace, values, option_string))
   ...         setattr(namespace, self.dest, values)
   ...
   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', action=FooAction)
   >>> parser.add_argument('bar', action=FooAction)
   >>> args = parser.parse_args('1 --foo 2'.split())
   Namespace(bar=None, foo=None) '1' None
   Namespace(bar='1', foo=None) '2' '--foo'
   >>> args
   Namespace(bar='1', foo='2')

詳細は "Action" を参照してください。


nargs
-----

ArgumentParser objects usually associate a single command-line
argument with a single action to be taken.  The "nargs" keyword
argument associates a different number of command-line arguments with
a single action.  The supported values are:

* "N" (整数) -- "N" 個の引数がコマンドラインから集められ、リストに格納
  されます。例えば:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', nargs=2)
     >>> parser.add_argument('bar', nargs=1)
     >>> parser.parse_args('c --foo a b'.split())
     Namespace(bar=['c'], foo=['a', 'b'])

  "nargs=1" は1要素のリストを作ることに注意してください。これはデフォ
  ルトの、要素がそのまま属性になる動作とは異なります。

* "'?'" -- 可能なら1つの引数がコマンドラインから取られ、1つのアイテム
  を作ります。コマンドライン引数が存在しない場合、default の値が生成さ
  れます。オプション引数の場合、さらにオプション引数が指定され、その後
  にコマンドライン引数がないというケースもありえます。この場合は const
  の値が生成されます。この動作の例です:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
     >>> parser.add_argument('bar', nargs='?', default='d')
     >>> parser.parse_args(['XX', '--foo', 'YY'])
     Namespace(bar='XX', foo='YY')
     >>> parser.parse_args(['XX', '--foo'])
     Namespace(bar='XX', foo='c')
     >>> parser.parse_args([])
     Namespace(bar='d', foo='d')

  "nargs='?'" のよくある利用例の1つは、入出力ファイルの指定オプション
  です:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
     ...                     default=sys.stdin)
     >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
     ...                     default=sys.stdout)
     >>> parser.parse_args(['input.txt', 'output.txt'])
     Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
               outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
     >>> parser.parse_args([])
     Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
               outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)

* "'*'" -- すべてのコマンドライン引数がリストに集められます。複数の位
  置引数が "nargs='*'" を持つことにあまり意味はありませんが、複数のオ
  プション引数が "nargs='*'" を持つことはありえます。例えば:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', nargs='*')
     >>> parser.add_argument('--bar', nargs='*')
     >>> parser.add_argument('baz', nargs='*')
     >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
     Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])

* "'+'" -- "'*'" と同じように、すべてのコマンドライン引数をリストに集
  めます。加えて、最低でも1つのコマンドライン引数が存在しない場合にエ
  ラーメッセージを生成します。例えば:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('foo', nargs='+')
     >>> parser.parse_args(['a', 'b'])
     Namespace(foo=['a', 'b'])
     >>> parser.parse_args([])
     usage: PROG [-h] foo [foo ...]
     PROG: error: the following arguments are required: foo

If the "nargs" keyword argument is not provided, the number of
arguments consumed is determined by the action.  Generally this means
a single command-line argument will be consumed and a single item (not
a list) will be produced.


const
-----

"add_argument()" の "const" 引数は、コマンドライン引数から読み込まれな
いけれども "ArgumentParser" のいくつかのアクションで必要とされる値のた
めに使われます。この引数のよくある2つの使用法は:

* "add_argument()" が "action='store_const'" か
  "action='append_const'" で呼び出されたとき、これらのアクションは
  "const" の値を "parse_args()" が返すオブジェクトの属性に追加します。
  サンプルは action の説明を参照してください。"const" が
  "add_argument()" に与えられなければ、"None" のデフォルト値を受け取り
  ます。

* "add_argument()" がオプション文字列 ("-f" や "--foo") と "nargs='?'"
  で呼び出された場合。この場合0個か1つのコマンドライン引数を取るオプシ
  ョン引数が作られます。オプション引数にコマンドライン引数が続かなかっ
  た場合、代わりに "const" の値が "None" であると見なされます。サンプ
  ルは nargs の説明を参照してください。

バージョン 3.11 で変更: "action='append_const'" や
"action='store_const'" の場合も含め、デフォルトでは "const=None" です
。


default
-------

すべてのオプション引数といくつかの位置引数はコマンドライン上で省略され
ることがあります。 "add_argument()" の "default" キーワード引数 (デフ
ォルト: "None") は、コマンドライン引数が存在しなかった場合に利用する値
を指定します。オプション引数では、オプション文字列がコマンドライン上に
存在しなかったときに "default" の値が利用されます:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', default=42)
   >>> parser.parse_args(['--foo', '2'])
   Namespace(foo='2')
   >>> parser.parse_args([])
   Namespace(foo=42)

If the target namespace already has an attribute set, the action
*default* will not over write it:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', default=42)
   >>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
   Namespace(foo=101)

"default" の値が文字列の場合、パーサーは値をコマンドライン引数のように
解析します。具体的には、パーサーは返り値 "Namespace" の属性を設定する
前に、type 変換引数が与えられていればそれらを適用します。そうでない場
合、パーサーは値をそのまま使用します:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--length', default='10', type=int)
   >>> parser.add_argument('--width', default=10.5, type=int)
   >>> parser.parse_args()
   Namespace(length=10, width=10.5)

nargs が "?" か "*" である位置引数では、コマンドライン引数が指定されな
かった場合 "default" の値が使われます。例えば:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('foo', nargs='?', default=42)
   >>> parser.parse_args(['a'])
   Namespace(foo='a')
   >>> parser.parse_args([])
   Namespace(foo=42)

"default=argparse.SUPPRESS" を渡すと、コマンドライン引数が存在しないと
きに属性の追加をしなくなります:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
   >>> parser.parse_args([])
   Namespace()
   >>> parser.parse_args(['--foo', '1'])
   Namespace(foo='1')


type
----

デフォルトでは、パーサーはコマンドライン引数を単なる文字列として読み込
みます。しかし、それらの文字列を "float", "int" など別の型として扱うべ
き事がよくあります。"add_argument()" の "type" キーワード引数に指定す
る type converter により、必要な型チェックと型変換を行うことができます
。

もし type キーワードが default キーワードとともに使用された場合、
default  の値が文字列のときのみ、type converter による変換などが行われ
ます。

The argument to "type" can be any callable that accepts a single
string. If the function raises "ArgumentTypeError", "TypeError", or
"ValueError", the exception is caught and a nicely formatted error
message is displayed.  No other exception types are handled.

一般的なビルトインデータ型や関数を "type" 引数の値として直接指定できま
す:

   import argparse
   import pathlib

   parser = argparse.ArgumentParser()
   parser.add_argument('count', type=int)
   parser.add_argument('distance', type=float)
   parser.add_argument('street', type=ascii)
   parser.add_argument('code_point', type=ord)
   parser.add_argument('source_file', type=open)
   parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
   parser.add_argument('datapath', type=pathlib.Path)

ユーザが定義した関数も使用できます:

   >>> def hyphenated(string):
   ...     return '-'.join([word[:4] for word in string.casefold().split()])
   ...
   >>> parser = argparse.ArgumentParser()
   >>> _ = parser.add_argument('short_title', type=hyphenated)
   >>> parser.parse_args(['"The Tale of Two Cities"'])
   Namespace(short_title='"the-tale-of-two-citi')

Type converter として "bool()" 関数を使用することは推奨されません。な
ぜなら、これは空文字列を "False" に、それ以外の全てを "True" に変換し
ますが、これはおそらく望まれる動作ではないからです (訳注: 文字列
"'false'" を "False" に変換してくれたりはしません)。

一般論として、"type" キーワードに指定するものは、せいぜい上記の3種類の
例外を発生するくらいの、お手軽な変換に限るべきです。より複雑な
(interesting) エラー処理、またはリソース管理を伴うものは、引数を解析し
たあとに別個の処理として行うべきです。

たとえば、JSON または YAML からの変換は複雑なエラーケースを持つので、
"type" がサポートする以上のエラー表示を必要とするでしょう。(JSON デコ
ーダが発生しうる) "JSONDecodeError" は適切に整形されて表示されません。
また、"FileNotFoundError" が発生しても parser は何も処理しません。

Even "FileType" has its limitations for use with the "type" keyword.
If one argument uses *FileType* and then a subsequent argument fails,
an error is reported but the file is not automatically closed.  In
this case, it would be better to wait until after the parser has run
and then use the "with"-statement to manage the files.

なお、引数が、あらかじめ決められた値の候補のいずれかに一致するかをチェ
ックしたいだけの場合には、代わりに choices キーワードの使用を検討して
ください。


choices
-------

コマンドライン引数をいくつかの選択肢の中から選ばせたい場合があります。
これは "add_argument()" に シーケンスオブジェクトを *choices* キーワー
ド引数として渡すことで可能です。コマンドラインを解析するとき、引数の値
がチェックされ、その値が選択肢の中に含まれていない場合はエラーメッセー
ジを表示します:

   >>> parser = argparse.ArgumentParser(prog='game.py')
   >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
   >>> parser.parse_args(['rock'])
   Namespace(move='rock')
   >>> parser.parse_args(['fire'])
   usage: game.py [-h] {rock,paper,scissors}
   game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
   'paper', 'scissors')

Note that inclusion in the *choices* sequence is checked after any
type conversions have been performed, so the type of the objects in
the *choices* sequence should match the type specified:

   >>> parser = argparse.ArgumentParser(prog='doors.py')
   >>> parser.add_argument('door', type=int, choices=range(1, 4))
   >>> print(parser.parse_args(['3']))
   Namespace(door=3)
   >>> parser.parse_args(['4'])
   usage: doors.py [-h] {1,2,3}
   doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

任意のシーケンスを *choices* に渡すことができます。すなわち、"list" オ
ブジェクト、 "tuple" オブジェクト、カスタムシーケンスはすべてサポート
されています。

ただし、"enum.Enum" を渡すことは推奨されません。使用方法、ヘルプ、エラ
ーメッセージなどでどのように表示されるかを制御することが難いからです。

ヘルプテキストにおいて整形された choices の値は、通常 *dest* から生成
されるデフォルトの *metavar* に優先します。ユーザーは *dest* パラメー
タを目にすることがないため、この振る舞いは基本的には望ましいものです。
もしこの表示方法が望ましくない場合 (おそらく多くの選択肢がある場合など
) は、 metavar を明示的に指定してください。


required
--------

In general, the "argparse" module assumes that flags like "-f" and "--
bar" indicate *optional* arguments, which can always be omitted at the
command line. To make an option *required*, "True" can be specified
for the "required=" keyword argument to "add_argument()":

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', required=True)
   >>> parser.parse_args(['--foo', 'BAR'])
   Namespace(foo='BAR')
   >>> parser.parse_args([])
   usage: [-h] --foo FOO
   : error: the following arguments are required: --foo

上の例のように、引数が "required" と指定されると、"parse_args()" はそ
のフラグがコマンドラインに存在しないときにエラーを表示します。

注釈:

  ユーザーは、通常 *フラグ* の指定は *任意* であると認識しているため、
  必須にするのは一般的には悪いやり方で、できる限り避けるべきです。


help
----

The "help" value is a string containing a brief description of the
argument. When a user requests help (usually by using "-h" or "--help"
at the command line), these "help" descriptions will be displayed with
each argument:

   >>> parser = argparse.ArgumentParser(prog='frobble')
   >>> parser.add_argument('--foo', action='store_true',
   ...                     help='foo the bars before frobbling')
   >>> parser.add_argument('bar', nargs='+',
   ...                     help='one of the bars to be frobbled')
   >>> parser.parse_args(['-h'])
   usage: frobble [-h] [--foo] bar [bar ...]

   positional arguments:
    bar     one of the bars to be frobbled

   options:
    -h, --help  show this help message and exit
    --foo   foo the bars before frobbling

"help" 文字列には、プログラム名や引数の default などを繰り返し記述する
のを避けるためのフォーマット指定子を含めることができます。利用できる指
定子には、プログラム名 "%(prog)s" と、 "%(default)s" や "%(type)s" な
ど "add_argument()" のキーワード引数の多くが含まれます:

   >>> parser = argparse.ArgumentParser(prog='frobble')
   >>> parser.add_argument('bar', nargs='?', type=int, default=42,
   ...                     help='the bar to %(prog)s (default: %(default)s)')
   >>> parser.print_help()
   usage: frobble [-h] [bar]

   positional arguments:
    bar     the bar to frobble (default: 42)

   options:
    -h, --help  show this help message and exit

ヘルプ文字列は %-フォーマットをサポートしているので、ヘルプ文字列内に
リテラル "%" を表示したい場合は "%%" のようにエスケープしなければなり
ません。

"argparse" supports silencing the help entry for certain options, by
setting the "help" value to "argparse.SUPPRESS":

   >>> parser = argparse.ArgumentParser(prog='frobble')
   >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
   >>> parser.print_help()
   usage: frobble [-h]

   options:
     -h, --help  show this help message and exit


metavar
-------

When "ArgumentParser" generates help messages, it needs some way to
refer to each expected argument.  By default, ArgumentParser objects
use the dest value as the "name" of each object.  By default, for
positional argument actions, the dest value is used directly, and for
optional argument actions, the dest value is uppercased.  So, a single
positional argument with "dest='bar'" will be referred to as "bar". A
single optional argument "--foo" that should be followed by a single
command-line argument will be referred to as "FOO".  An example:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo')
   >>> parser.add_argument('bar')
   >>> parser.parse_args('X --foo Y'.split())
   Namespace(bar='X', foo='Y')
   >>> parser.print_help()
   usage:  [-h] [--foo FOO] bar

   positional arguments:
    bar

   options:
    -h, --help  show this help message and exit
    --foo FOO

代わりの名前を、"metavar" として指定できます:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', metavar='YYY')
   >>> parser.add_argument('bar', metavar='XXX')
   >>> parser.parse_args('X --foo Y'.split())
   Namespace(bar='X', foo='Y')
   >>> parser.print_help()
   usage:  [-h] [--foo YYY] XXX

   positional arguments:
    XXX

   options:
    -h, --help  show this help message and exit
    --foo YYY

"metavar" は *表示される* 名前だけを変更することに注意してください。
"parse_args()" の返すオブジェクトの属性名は dest の値のままです。

"nargs" を指定した場合、metavar が複数回利用されるかもしれません。
"metavar" にタプルを渡すと、各引数に対して異なる名前を指定できます:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x', nargs=2)
   >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
   >>> parser.print_help()
   usage: PROG [-h] [-x X X] [--foo bar baz]

   options:
    -h, --help     show this help message and exit
    -x X X
    --foo bar baz


dest
----

ほとんどの "ArgumentParser" のアクションは "parse_args()" が返すオブジ
ェクトに対する属性として値を追加します。この属性の名前は
"add_argument()" の "dest" キーワード引数によって決定されます。位置引
数のアクションについては、 "dest" は通常 "add_argument()" の第一引数と
して渡します:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('bar')
   >>> parser.parse_args(['XXX'])
   Namespace(bar='XXX')

オプション引数のアクションについては、 "dest" の値は通常オプション文字
列から生成されます。 "ArgumentParser" は最初の長いオプション文字列を選
択し、先頭の "--" を除去することで "dest" の値を生成します。長いオプシ
ョン文字列が指定されていない場合、最初の短いオプション文字列から先頭の
"-" 文字を除去することで "dest" を生成します。先頭以外のすべての "-"
文字は、妥当な属性名になるように "_" 文字へ変換されます。次の例はこの
動作を示しています:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('-f', '--foo-bar', '--foo')
   >>> parser.add_argument('-x', '-y')
   >>> parser.parse_args('-f 1 -x 2'.split())
   Namespace(foo_bar='1', x='2')
   >>> parser.parse_args('--foo 1 -y 2'.split())
   Namespace(foo_bar='1', x='2')

"dest" にカスタムの属性名を与えることも可能です:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', dest='bar')
   >>> parser.parse_args('--foo XXX'.split())
   Namespace(bar='XXX')


Action クラス
-------------

Action classes implement the Action API, a callable which returns a
callable which processes arguments from the command-line. Any object
which follows this API may be passed as the "action" parameter to
"add_argument()".

class argparse.Action(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Action objects are used by an ArgumentParser to represent the
information needed to parse a single argument from one or more strings
from the command line. The Action class must accept the two positional
arguments plus any keyword arguments passed to
"ArgumentParser.add_argument()" except for the "action" itself.

Instances of Action (or return value of any callable to the "action"
parameter) should have attributes "dest", "option_strings", "default",
"type", "required", "help", etc. defined. The easiest way to ensure
these attributes are defined is to call "Action.__init__".

Action instances should be callable, so subclasses must override the
"__call__" method, which should accept four parameters:

* "parser" - The ArgumentParser object which contains this action.

* "namespace" - The "Namespace" object that will be returned by
  "parse_args()".  Most actions add an attribute to this object using
  "setattr()".

* "values" - The associated command-line arguments, with any type
  conversions applied.  Type conversions are specified with the type
  keyword argument to "add_argument()".

* "option_string" - The option string that was used to invoke this
  action. The "option_string" argument is optional, and will be absent
  if the action is associated with a positional argument.

The "__call__" method may perform arbitrary actions, but will
typically set attributes on the "namespace" based on "dest" and
"values".

Action subclasses can define a "format_usage" method that takes no
argument and return a string which will be used when printing the
usage of the program. If such method is not provided, a sensible
default will be used.


parse_args() メソッド
=====================

ArgumentParser.parse_args(args=None, namespace=None)

   引数の文字列をオブジェクトに変換し、namespace オブジェクトの属性に
   代入します。結果の namespace オブジェクトを返します。

   Previous calls to "add_argument()" determine exactly what objects
   are created and how they are assigned. See the documentation for
   "add_argument()" for details.

   * args - 解析する文字列のリスト。デフォルトでは "sys.argv" から取得
     されます。

   * namespace - 属性を代入するオブジェクト。デフォルトでは、新しい空
     の "Namespace" オブジェクトです。


オプション値の文法
------------------

"parse_args()" メソッドは、オプションの値がある場合、そのオプションの
値の指定に複数の方法をサポートしています。もっとも単純な場合には、オプ
ションとその値は次のように2つの別々の引数として渡されます:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x')
   >>> parser.add_argument('--foo')
   >>> parser.parse_args(['-x', 'X'])
   Namespace(foo=None, x='X')
   >>> parser.parse_args(['--foo', 'FOO'])
   Namespace(foo='FOO', x=None)

長いオプション (1文字よりも長い名前を持ったオプション) では、オプショ
ンとその値は次のように "=" で区切られた1つのコマンドライン引数として渡
すこともできます:

   >>> parser.parse_args(['--foo=FOO'])
   Namespace(foo='FOO', x=None)

短いオプション (1文字のオプション) では、オプションとその値は次のよう
に連結して渡すことができます:

   >>> parser.parse_args(['-xX'])
   Namespace(foo=None, x='X')

最後の1つのオプションだけが値を要求する場合、または値を要求するオプシ
ョンがない場合、複数の短いオプションは次のように1つの接頭辞 "-" だけで
連結できます:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x', action='store_true')
   >>> parser.add_argument('-y', action='store_true')
   >>> parser.add_argument('-z')
   >>> parser.parse_args(['-xyzZ'])
   Namespace(x=True, y=True, z='Z')


不正な引数
----------

"parse_args()" は、コマンドラインの解析中に、曖昧なオプション、不正な
型、不正なオプション、位置引数の数の不一致などのエラーを検証します。そ
れらのエラーが発生した場合、エラーメッセージと使用法メッセージを表示し
て終了します:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('--foo', type=int)
   >>> parser.add_argument('bar', nargs='?')

   >>> # invalid type
   >>> parser.parse_args(['--foo', 'spam'])
   usage: PROG [-h] [--foo FOO] [bar]
   PROG: error: argument --foo: invalid int value: 'spam'

   >>> # invalid option
   >>> parser.parse_args(['--bar'])
   usage: PROG [-h] [--foo FOO] [bar]
   PROG: error: no such option: --bar

   >>> # wrong number of arguments
   >>> parser.parse_args(['spam', 'badger'])
   usage: PROG [-h] [--foo FOO] [bar]
   PROG: error: extra arguments found: badger


"-" を含む引数
--------------

"parse_args()" メソッドは、ユーザーが明らかなミスをした場合はエラーを
表示しますが、いくつか本質的に曖昧な場面があります。例えば、コマンドラ
イン引数 "-1" は、オプションの指定かもしれませんし位置引数かもしれませ
ん。"parse_args()" メソッドはこれを次のように扱います: 負の数として解
釈でき、パーサーに負の数のように解釈できるオプションが存在しない場合に
のみ、"-" で始まる位置引数になりえます:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x')
   >>> parser.add_argument('foo', nargs='?')

   >>> # no negative number options, so -1 is a positional argument
   >>> parser.parse_args(['-x', '-1'])
   Namespace(foo=None, x='-1')

   >>> # no negative number options, so -1 and -5 are positional arguments
   >>> parser.parse_args(['-x', '-1', '-5'])
   Namespace(foo='-5', x='-1')

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-1', dest='one')
   >>> parser.add_argument('foo', nargs='?')

   >>> # negative number options present, so -1 is an option
   >>> parser.parse_args(['-1', 'X'])
   Namespace(foo=None, one='X')

   >>> # negative number options present, so -2 is an option
   >>> parser.parse_args(['-2'])
   usage: PROG [-h] [-1 ONE] [foo]
   PROG: error: no such option: -2

   >>> # negative number options present, so both -1s are options
   >>> parser.parse_args(['-1', '-1'])
   usage: PROG [-h] [-1 ONE] [foo]
   PROG: error: argument -1: expected one argument

"-" で始まる位置引数があって、それが負の数として解釈できない場合、ダミ
ーの引数 "'--'" を挿入して、"parse_args()" にそれ以降のすべてが位置引
数だと教えることができます:

   >>> parser.parse_args(['--', '-f'])
   Namespace(foo='-f', one=None)


引数の短縮形 (先頭文字でのマッチング)
-------------------------------------

"parse_args()" メソッドは、デフォルトで、長いオプションに曖昧さがない
(先頭文字列が一意である) かぎり、先頭文字列に短縮して指定できます:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-bacon')
   >>> parser.add_argument('-badger')
   >>> parser.parse_args('-bac MMM'.split())
   Namespace(bacon='MMM', badger=None)
   >>> parser.parse_args('-bad WOOD'.split())
   Namespace(bacon=None, badger='WOOD')
   >>> parser.parse_args('-ba BA'.split())
   usage: PROG [-h] [-bacon BACON] [-badger BADGER]
   PROG: error: ambiguous option: -ba could match -badger, -bacon

先頭の文字が同じ引数が複数ある場合に短縮指定を行うとエラーを発生させま
す。この機能は allow_abbrev に "False" を指定することで無効にできます
。


"sys.argv" 以外
---------------

Sometimes it may be useful to have an ArgumentParser parse arguments
other than those of "sys.argv".  This can be accomplished by passing a
list of strings to "parse_args()".  This is useful for testing at the
interactive prompt:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument(
   ...     'integers', metavar='int', type=int, choices=range(10),
   ...     nargs='+', help='an integer in the range 0..9')
   >>> parser.add_argument(
   ...     '--sum', dest='accumulate', action='store_const', const=sum,
   ...     default=max, help='sum the integers (default: find the max)')
   >>> parser.parse_args(['1', '2', '3', '4'])
   Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
   >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
   Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])


Namespace オブジェクト
----------------------

class argparse.Namespace

   "parse_args()" が属性を格納して返すためのオブジェクトにデフォルトで
   使用されるシンプルなクラスです。

このクラスはシンプルに設計されており、単に読みやすい文字列表現を持った
"object" のサブクラスです。もし属性を辞書のように扱える方が良ければ、
標準的な Python のイディオム "vars()" を利用できます:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo')
   >>> args = parser.parse_args(['--foo', 'BAR'])
   >>> vars(args)
   {'foo': 'BAR'}

"ArgumentParser" が、新しい "Namespace" オブジェクトではなく、既存のオ
ブジェクトに属性を設定する方が良い場合があります。これは "namespace="
キーワード引数を指定することで可能です:

   >>> class C:
   ...     pass
   ...
   >>> c = C()
   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo')
   >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
   >>> c.foo
   'BAR'


その他のユーティリティ
======================


サブコマンド
------------

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_strings][, dest][, required][, help][, metavar])

   Many programs split up their functionality into a number of sub-
   commands, for example, the "svn" program can invoke sub-commands
   like "svn checkout", "svn update", and "svn commit".  Splitting up
   functionality this way can be a particularly good idea when a
   program performs several different functions which require
   different kinds of command-line arguments. "ArgumentParser"
   supports the creation of such sub-commands with the
   "add_subparsers()" method.  The "add_subparsers()" method is
   normally called with no arguments and returns a special action
   object.  This object has a single method, "add_parser()", which
   takes a command name and any "ArgumentParser" constructor
   arguments, and returns an "ArgumentParser" object that can be
   modified as usual.

   引数の説明:

   * title - title for the sub-parser group in help output; by default
     "subcommands" if description is provided, otherwise uses title
     for positional arguments

   * description - description for the sub-parser group in help
     output, by default "None"

   * prog - usage information that will be displayed with sub-command
     help, by default the name of the program and any positional
     arguments before the subparser argument

   * parser_class - class which will be used to create sub-parser
     instances, by default the class of the current parser (e.g.
     ArgumentParser)

   * action - コマンドラインにこの引数があったときの基本のアクション。

   * dest - サブコマンド名を格納する属性の名前です。デフォルトは
     "None" で値は格納されません

   * required - サブコマンドが必須であるかどうかを指定し、デフォルトは
     "False" です。(3.7 より追加)

   * help - ヘルプ出力に表示されるサブパーサーグループのヘルプです。デ
     フォルトは "None" です

   * metavar - string presenting available sub-commands in help; by
     default it is "None" and presents sub-commands in form {cmd1,
     cmd2, ..}

   いくつかの使用例:

      >>> # create the top-level parser
      >>> parser = argparse.ArgumentParser(prog='PROG')
      >>> parser.add_argument('--foo', action='store_true', help='foo help')
      >>> subparsers = parser.add_subparsers(help='sub-command help')
      >>>
      >>> # create the parser for the "a" command
      >>> parser_a = subparsers.add_parser('a', help='a help')
      >>> parser_a.add_argument('bar', type=int, help='bar help')
      >>>
      >>> # create the parser for the "b" command
      >>> parser_b = subparsers.add_parser('b', help='b help')
      >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
      >>>
      >>> # parse some argument lists
      >>> parser.parse_args(['a', '12'])
      Namespace(bar=12, foo=False)
      >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
      Namespace(baz='Z', foo=True)

   "parse_args()" が返すオブジェクトにはメインパーサーとコマンドライン
   で選択されたサブパーサーによる属性だけが設定されており、選択されな
   かったサブコマンドのパーサーの属性が設定されていないことに注意して
   ください。このため、上の例では、"a" コマンドが指定されたときは
   "foo", "bar" 属性だけが存在し、"b" コマンドが指定されたときは
   "foo", "baz" 属性だけが存在しています。

   同じように、サブパーサーにヘルプメッセージが要求された場合は、その
   パーサーに対するヘルプだけが表示されます。ヘルプメッセージには親パ
   ーサーや兄弟パーサーのヘルプメッセージを表示しません。 (ただし、各
   サブパーサーコマンドのヘルプメッセージは、上の例にもあるように
   "add_parser()" の "help=" 引数によって指定できます)

      >>> parser.parse_args(['--help'])
      usage: PROG [-h] [--foo] {a,b} ...

      positional arguments:
        {a,b}   sub-command help
          a     a help
          b     b help

      options:
        -h, --help  show this help message and exit
        --foo   foo help

      >>> parser.parse_args(['a', '--help'])
      usage: PROG a [-h] bar

      positional arguments:
        bar     bar help

      options:
        -h, --help  show this help message and exit

      >>> parser.parse_args(['b', '--help'])
      usage: PROG b [-h] [--baz {X,Y,Z}]

      options:
        -h, --help     show this help message and exit
        --baz {X,Y,Z}  baz help

   "add_subparsers()" メソッドは "title" と "description" キーワード引
   数もサポートしています。どちらかが存在する場合、サブパーサーのコマ
   ンドはヘルプ出力でそれぞれのグループの中に表示されます。例えば:

      >>> parser = argparse.ArgumentParser()
      >>> subparsers = parser.add_subparsers(title='subcommands',
      ...                                    description='valid subcommands',
      ...                                    help='additional help')
      >>> subparsers.add_parser('foo')
      >>> subparsers.add_parser('bar')
      >>> parser.parse_args(['-h'])
      usage:  [-h] {foo,bar} ...

      options:
        -h, --help  show this help message and exit

      subcommands:
        valid subcommands

        {foo,bar}   additional help

   Furthermore, "add_parser" supports an additional "aliases"
   argument, which allows multiple strings to refer to the same
   subparser. This example, like "svn", aliases "co" as a shorthand
   for "checkout":

      >>> parser = argparse.ArgumentParser()
      >>> subparsers = parser.add_subparsers()
      >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
      >>> checkout.add_argument('foo')
      >>> parser.parse_args(['co', 'bar'])
      Namespace(foo='bar')

   One particularly effective way of handling sub-commands is to
   combine the use of the "add_subparsers()" method with calls to
   "set_defaults()" so that each subparser knows which Python function
   it should execute.  For example:

      >>> # sub-command functions
      >>> def foo(args):
      ...     print(args.x * args.y)
      ...
      >>> def bar(args):
      ...     print('((%s))' % args.z)
      ...
      >>> # create the top-level parser
      >>> parser = argparse.ArgumentParser()
      >>> subparsers = parser.add_subparsers(required=True)
      >>>
      >>> # create the parser for the "foo" command
      >>> parser_foo = subparsers.add_parser('foo')
      >>> parser_foo.add_argument('-x', type=int, default=1)
      >>> parser_foo.add_argument('y', type=float)
      >>> parser_foo.set_defaults(func=foo)
      >>>
      >>> # create the parser for the "bar" command
      >>> parser_bar = subparsers.add_parser('bar')
      >>> parser_bar.add_argument('z')
      >>> parser_bar.set_defaults(func=bar)
      >>>
      >>> # parse the args and call whatever function was selected
      >>> args = parser.parse_args('foo 1 -x 2'.split())
      >>> args.func(args)
      2.0
      >>>
      >>> # parse the args and call whatever function was selected
      >>> args = parser.parse_args('bar XYZYX'.split())
      >>> args.func(args)
      ((XYZYX))

   こうすると、"parse_args()" が引数の解析が終わってから適切な関数を呼
   び出すようになります。このように関数をアクションに関連付けるのは一
   般的にサブパーサーごとに異なるアクションを扱うもっとも簡単な方法で
   す。ただし、実行されたサブパーサーの名前を確認する必要がある場合は
   、"add_subparsers()" を呼び出すときに "dest" キーワードを指定できま
   す:

      >>> parser = argparse.ArgumentParser()
      >>> subparsers = parser.add_subparsers(dest='subparser_name')
      >>> subparser1 = subparsers.add_parser('1')
      >>> subparser1.add_argument('-x')
      >>> subparser2 = subparsers.add_parser('2')
      >>> subparser2.add_argument('y')
      >>> parser.parse_args(['2', 'frobble'])
      Namespace(subparser_name='2', y='frobble')

   バージョン 3.7 で変更: New *required* keyword argument.


FileType オブジェクト
---------------------

class argparse.FileType(mode='r', bufsize=-1, encoding=None, errors=None)

   "FileType" ファクトリは "ArgumentParser.add_argument()" の type 引
   数に渡すことができるオブジェクトを生成します。 type が "FileType"
   オブジェクトである引数はコマンドライン引数を、指定されたモード、バ
   ッファーサイズ、エンコーディング、エラー処理でファイルとして開きま
   す (詳細は "open()" 関数を参照してください。):

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
      >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
      >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
      Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)

   FileType オブジェクトは擬似引数 "'-'" を識別し、読み込み用の
   "FileType" であれば "sys.stdin" を、書き込み用の "FileType" であれ
   ば "sys.stdout" に変換します:

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('infile', type=argparse.FileType('r'))
      >>> parser.parse_args(['-'])
      Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)

   バージョン 3.4 で変更: *encodings* と *errors* がパラメータに追加さ
   れました。


引数グループ
------------

ArgumentParser.add_argument_group(title=None, description=None)

   By default, "ArgumentParser" groups command-line arguments into
   "positional arguments" and "options" when displaying help messages.
   When there is a better conceptual grouping of arguments than this
   default one, appropriate groups can be created using the
   "add_argument_group()" method:

      >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
      >>> group = parser.add_argument_group('group')
      >>> group.add_argument('--foo', help='foo help')
      >>> group.add_argument('bar', help='bar help')
      >>> parser.print_help()
      usage: PROG [--foo FOO] bar

      group:
        bar    bar help
        --foo FOO  foo help

   The "add_argument_group()" method returns an argument group object
   which has an "add_argument()" method just like a regular
   "ArgumentParser".  When an argument is added to the group, the
   parser treats it just like a normal argument, but displays the
   argument in a separate group for help messages.  The
   "add_argument_group()" method accepts *title* and *description*
   arguments which can be used to customize this display:

      >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
      >>> group1 = parser.add_argument_group('group1', 'group1 description')
      >>> group1.add_argument('foo', help='foo help')
      >>> group2 = parser.add_argument_group('group2', 'group2 description')
      >>> group2.add_argument('--bar', help='bar help')
      >>> parser.print_help()
      usage: PROG [--bar BAR] foo

      group1:
        group1 description

        foo    foo help

      group2:
        group2 description

        --bar BAR  bar help

   ユーザー定義グループにないすべての引数は通常の "位置引数" と "オプ
   ション引数" セクションに表示されます。

   バージョン 3.11 で変更: Calling "add_argument_group()" on an
   argument group is deprecated. This feature was never supported and
   does not always work correctly. The function exists on the API by
   accident through inheritance and will be removed in the future.


相互排他
--------

ArgumentParser.add_mutually_exclusive_group(required=False)

   Create a mutually exclusive group. "argparse" will make sure that
   only one of the arguments in the mutually exclusive group was
   present on the command line:

      >>> parser = argparse.ArgumentParser(prog='PROG')
      >>> group = parser.add_mutually_exclusive_group()
      >>> group.add_argument('--foo', action='store_true')
      >>> group.add_argument('--bar', action='store_false')
      >>> parser.parse_args(['--foo'])
      Namespace(bar=True, foo=True)
      >>> parser.parse_args(['--bar'])
      Namespace(bar=False, foo=False)
      >>> parser.parse_args(['--foo', '--bar'])
      usage: PROG [-h] [--foo | --bar]
      PROG: error: argument --bar: not allowed with argument --foo

   "add_mutually_exclusive_group()" メソッドの引数 *required* に True
   値を指定すると、その相互排他引数のどれか1つを選ぶことが要求されます
   :

      >>> parser = argparse.ArgumentParser(prog='PROG')
      >>> group = parser.add_mutually_exclusive_group(required=True)
      >>> group.add_argument('--foo', action='store_true')
      >>> group.add_argument('--bar', action='store_false')
      >>> parser.parse_args([])
      usage: PROG [-h] (--foo | --bar)
      PROG: error: one of the arguments --foo --bar is required

   Note that currently mutually exclusive argument groups do not
   support the *title* and *description* arguments of
   "add_argument_group()".

   バージョン 3.11 で変更: Calling "add_argument_group()" or
   "add_mutually_exclusive_group()" on a mutually exclusive group is
   deprecated. These features were never supported and do not always
   work correctly. The functions exist on the API by accident through
   inheritance and will be removed in the future.


パーサーのデフォルト値
----------------------

ArgumentParser.set_defaults(**kwargs)

   ほとんどの場合、 "parse_args()" が返すオブジェクトの属性はコマンド
   ライン引数の内容と引数のアクションによってのみ決定されます。
   "set_defaults()" を使うと与えられたコマンドライン引数の内容によらず
   追加の属性を決定することが可能です:

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('foo', type=int)
      >>> parser.set_defaults(bar=42, baz='badger')
      >>> parser.parse_args(['736'])
      Namespace(bar=42, baz='badger', foo=736)

   パーサーレベルのデフォルト値は常に引数レベルのデフォルト値を上書き
   します:

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--foo', default='bar')
      >>> parser.set_defaults(foo='spam')
      >>> parser.parse_args([])
      Namespace(foo='spam')

   パーサーレベルの default は、複数のパーサーを扱うときに特に便利です
   。このタイプの例については "add_subparsers()" メソッドを参照してく
   ださい。

ArgumentParser.get_default(dest)

   "add_argument()" か "set_defaults()" によって指定された、 namespace
   の属性のデフォルト値を取得します:

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--foo', default='badger')
      >>> parser.get_default('foo')
      'badger'


ヘルプの表示
------------

ほとんどの典型的なアプリケーションでは、"parse_args()" が使用法やエラ
ーメッセージのフォーマットと表示について面倒を見ます。しかし、いくつか
のフォーマットメソッドが利用できます:

ArgumentParser.print_usage(file=None)

   "ArgumentParser" がコマンドラインからどう実行されるべきかの短い説明
   を表示します。 *file* が "None" の時は、 "sys.stdout" に出力されま
   す。

ArgumentParser.print_help(file=None)

   プログラムの使用法と "ArgumentParser" に登録された引数についての情
   報を含むヘルプメッセージを表示します。 *file* が "None" の時は、
   "sys.stdout" に出力されます。

これらのメソッドの、表示する代わりにシンプルに文字列を返すバージョンも
あります:

ArgumentParser.format_usage()

   "ArgumentParser" がコマンドラインからどう実行されるべきかの短い説明
   を格納した文字列を返します。

ArgumentParser.format_help()

   プログラムの使用法と "ArgumentParser" に登録された引数についての情
   報を含むヘルプメッセージを格納した文字列を返します。


部分解析
--------

ArgumentParser.parse_known_args(args=None, namespace=None)

ときどき、スクリプトがコマンドライン引数のいくつかだけを解析し、残りの
引数は別のスクリプトやプログラムに渡すことがあります。こういった場合、
"parse_known_args()" メソッドが便利です。これは "parse_args()" と同じ
ように動作しますが、余分な引数が存在してもエラーを生成しません。代わり
に、評価された namespace オブジェクトと、残りの引数文字列のリストから
なる2要素タプルを返します。

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', action='store_true')
   >>> parser.add_argument('bar')
   >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
   (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])

警告:

  先頭文字でのマッチング ルールは "parse_known_args()" にも適用されま
  す。たとえ既知のオプションの先頭文字に過ぎない場合でも、パーサは引数
  リストに残さずに、オプションを受け取る場合があります。


ファイル解析のカスタマイズ
--------------------------

ArgumentParser.convert_arg_line_to_args(arg_line)

   ファイルから引数を読み込む場合 ("ArgumentParser" コンストラクターの
   *fromfile_prefix_chars* キーワード引数を参照)、1行につき1つの引数を
   読み込みます。 "convert_arg_line_to_args()" を変更することでこの動
   作をカスタマイズできます。

   このメソッドは、引数ファイルから読まれた文字列である1つの引数
   *arg_line* を受け取ります。そしてその文字列を解析した結果の引数のリ
   ストを返します。このメソッドはファイルから1行読みこむごとに、順番に
   呼ばれます。

   このメソッドをオーバーライドすると便利なこととして、スペースで区切
   られた行の単語1つ1つを別々の引数として扱えます。次の例でその方法を
   示します:

      class MyArgumentParser(argparse.ArgumentParser):
          def convert_arg_line_to_args(self, arg_line):
              return arg_line.split()


終了メソッド
------------

ArgumentParser.exit(status=0, message=None)

   This method terminates the program, exiting with the specified
   *status* and, if given, it prints a *message* before that. The user
   can override this method to handle these steps differently:

      class ErrorCatchingArgumentParser(argparse.ArgumentParser):
          def exit(self, status=0, message=None):
              if status:
                  raise Exception(f'Exiting because of an error: {message}')
              exit(status)

ArgumentParser.error(message)

   This method prints a usage message including the *message* to the
   standard error and terminates the program with a status code of 2.


混在した引数の解析
------------------

ArgumentParser.parse_intermixed_args(args=None, namespace=None)

ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)

多くの Unix コマンドは、オプション引数と位置引数を混在させることを許し
ています。 "parse_intermixed_args()" と
"parse_known_intermixed_args()" メソッドは、このような方法での解析をサ
ポートしています。

These parsers do not support all the argparse features, and will raise
exceptions if unsupported features are used.  In particular,
subparsers, and mutually exclusive groups that include both optionals
and positionals are not supported.

この例は、"parse_known_args()" と "parse_intermixed_args()" の違いを表
しています: 前者は "['2', '3']" を、解析されない引数として返し、後者は
全ての位置引数を "rest" に入れて返しています:

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo')
   >>> parser.add_argument('cmd')
   >>> parser.add_argument('rest', nargs='*', type=int)
   >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
   (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
   >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
   Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])

"parse_known_intermixed_args()" は、解析した内容を含む名前空間と、残り
の引数を含んだリストの、2つの要素を持つタプルを返します。
"parse_intermixed_args()" は、解析されない引数が残された場合にはエラー
を送出します。

バージョン 3.7 で追加.


Upgrading optparse code
=======================

Originally, the "argparse" module had attempted to maintain
compatibility with "optparse".  However, "optparse" was difficult to
extend transparently, particularly with the changes required to
support the new "nargs=" specifiers and better usage messages.  When
most everything in "optparse" had either been copy-pasted over or
monkey-patched, it no longer seemed practical to try to maintain the
backwards compatibility.

The "argparse" module improves on the standard library "optparse"
module in a number of ways including:

* Handling positional arguments.

* Supporting sub-commands.

* Allowing alternative option prefixes like "+" and "/".

* Handling zero-or-more and one-or-more style arguments.

* Producing more informative usage messages.

* Providing a much simpler interface for custom "type" and "action".

A partial upgrade path from "optparse" to "argparse":

* Replace all "optparse.OptionParser.add_option()" calls with
  "ArgumentParser.add_argument()" calls.

* Replace "(options, args) = parser.parse_args()" with "args =
  parser.parse_args()" and add additional
  "ArgumentParser.add_argument()" calls for the positional arguments.
  Keep in mind that what was previously called "options", now in the
  "argparse" context is called "args".

* Replace "optparse.OptionParser.disable_interspersed_args()" by using
  "parse_intermixed_args()" instead of "parse_args()".

* Replace callback actions and the "callback_*" keyword arguments with
  "type" or "action" arguments.

* Replace string names for "type" keyword arguments with the
  corresponding type objects (e.g. int, float, complex, etc).

* Replace "optparse.Values" with "Namespace" and
  "optparse.OptionError" and "optparse.OptionValueError" with
  "ArgumentError".

* Replace strings with implicit arguments such as "%default" or
  "%prog" with the standard Python syntax to use dictionaries to
  format strings, that is, "%(default)s" and "%(prog)s".

* Replace the OptionParser constructor "version" argument with a call
  to "parser.add_argument('--version', action='version', version='<the
  version>')".


例外
====

exception argparse.ArgumentError

   引数 (オプション引数または位置引数) の生成時または利用時のエラーで
   す。

   この例外の文字列表現は、エラーの原因となった引数についての情報を補
   足するメッセージです。

exception argparse.ArgumentTypeError

   コマンドラインの文字列を、指定された型に変換するのに失敗した時に送
   出されます。
