"argparse" --- コマンドラインオプションや引数、サブコマンド向けのパーサー
*************************************************************************

Added in version 3.2.

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

注釈:

  While "argparse" is the default recommended standard library module
  for implementing basic command line applications, authors with more
  exacting requirements for exactly how their command line
  applications behave may find it doesn't provide the necessary level
  of control. Refer to Choosing an argument parsing library for
  alternatives to consider when "argparse" doesn't support behaviors
  that the application requires (such as entirely disabling support
  for interspersed options and positional arguments, or accepting
  option parameter values that start with "-" even when they
  correspond to another defined option).

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


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

このページは 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.

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 to 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')           # 位置引数
   parser.add_argument('-c', '--count')      # 値を取るオプション
   parser.add_argument('-v', '--verbose',
                       action='store_true')  # オン／オフフラグ

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

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

注釈:

  If you're looking for a guide about how to upgrade "optparse" code
  to "argparse", see Upgrading Optparse Code.


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, *, suggest_on_error=False, color=True)

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

   * prog - The name of the program (default: generated from the
     "__main__" module attributes and "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")

   * suggest_on_error - Enables suggestions for mistyped argument
     choices and subparser names (default: "False")

   * color - Allow color output (default: "True")

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

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

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

   バージョン 3.14 で変更: *suggest_on_error* and *color* parameters
   were added.

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


"prog"
------

By default, "ArgumentParser" calculates the name of the program to
display in help messages depending on the way the Python interpreter
was run:

* The "base name" of "sys.argv[0]" if a file was passed as argument.

* The Python interpreter name followed by "sys.argv[0]" if a directory
  or a zipfile was passed as argument.

* The Python interpreter name followed by "-m" followed by the module
  or package name if the "-m" option was used.

This default is almost always desirable because it will make the help
messages match the string that was used to invoke the program on the
command line. However, 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]",
from the "__main__" module attributes 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

バージョン 3.14 で変更: The default "prog" value now reflects how
"__main__" was actually executed, rather than always being
"os.path.basename(sys.argv[0])".


usage
-----

By default, "ArgumentParser" calculates the usage message from the
arguments it contains. 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" フォーマット指定子を、使用法メッセージ内でプログラム名とし
て利用できます。

When a custom usage message is specified for the main parser, you may
also want to consider passing  the "prog" argument to
"add_subparsers()" or the "prog" and the "usage" arguments to
"add_parser()", to ensure consistent command prefixes and usage
information across subparsers.


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.

デフォルトでは、説明は与えられたスペースに合わせて折り返されます。この
挙動を変更するには、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 newlines 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', encoding=sys.getfilesystemencoding()) 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')

Arguments read from a file must be one per line by default (but see
also "convert_arg_line_to_args()") and are treated as if they were in
the same place as the original file referencing argument on the
command line.  So in the example above, the expression "['-f', 'foo',
'@args.txt']" is considered equivalent to the expression "['-f',
'foo', '-f', 'bar']".

注釈:

  Empty lines are treated as empty strings ("''"), which are allowed
  as values but not as arguments. Empty lines that are read as
  arguments will result in an "unrecognized arguments" error.

"ArgumentParser" uses *filesystem encoding and error handler* to read
the file containing arguments.

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

バージョン 3.12 で変更: "ArgumentParser" changed encoding and errors
to read arguments files from default (e.g.
"locale.getpreferredencoding(False)" and ""strict"") to the
*filesystem encoding and error handler*. Arguments file should be
encoded in UTF-8 instead of ANSI Codepage on Windows.


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

Added in version 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. If "-h" or "--help" is supplied at
the command line, the "ArgumentParser" help will be printed.

必要に応じて、この 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 print a *message* to
"sys.stderr" and exit with a status code of 2.

もしエラーを例外としてプログラム内でキャッチしたい場合は、
"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

Added in version 3.9.


suggest_on_error
----------------

By default, when a user passes an invalid argument choice or subparser
name, "ArgumentParser" will exit with error info and list the
permissible argument choices (if specified) or subparser names as part
of the error message.

If the user would like to enable suggestions for mistyped argument
choices and subparser names, the feature can be enabled by setting
"suggest_on_error" to "True". Note that this only applies for
arguments when the choices specified are strings:

   >>> parser = argparse.ArgumentParser(description='Process some integers.',
                                        suggest_on_error=True)
   >>> parser.add_argument('--action', choices=['sum', 'max'])
   >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
   ...                     help='an integer for the accumulator')
   >>> parser.parse_args(['--action', 'sumn', 1, 2, 3])
   tester.py: error: argument --action: invalid choice: 'sumn', maybe you meant 'sum'? (choose from 'sum', 'max')

If you're writing code that needs to be compatible with older Python
versions and want to opportunistically use "suggest_on_error" when
it's available, you can set it as an attribute after initializing the
parser instead of using the keyword argument:

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

Added in version 3.14.


color
-----

By default, the help message is printed in color using ANSI escape
sequences. If you want plain text help messages, you can disable this
in your local environment, or in the argument parser itself by setting
"color" to "False":

   >>> parser = argparse.ArgumentParser(description='Process some integers.',
   ...                                  color=False)
   >>> parser.add_argument('--action', choices=['sum', 'max'])
   >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
   ...                     help='an integer for the accumulator')
   >>> parser.parse_args(['--help'])

Note that when "color=True", colored output depends on both
environment variables and terminal capabilities.  However, if
"color=False", colored output is always disabled, even if environment
variables like "FORCE_COLOR" are set.

注釈:

  Error messages will include color codes when redirecting stderr to a
  file. To avoid this, set the "NO_COLOR" or "PYTHON_COLORS"
  environment variable (for example, "NO_COLOR=1 python script.py 2>
  errors.txt").

Added in version 3.14.


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

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

   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()" が返すオブジェクトに追加される属性名。

   * deprecated - Whether or not use of the argument is deprecated.

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


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

By default, "argparse" automatically handles the internal naming and
display names of arguments, simplifying the process without requiring
additional configuration. As such, you do not need to specify the dest
and metavar parameters. The dest parameter defaults to the argument
name with underscores "_" replacing hyphens "-" . The metavar
parameter defaults to the upper-cased name. For example:

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('--foo-bar')
   >>> parser.parse_args(['--foo-bar', 'FOO-BAR'])
   Namespace(foo_bar='FOO-BAR')
   >>> parser.print_help()
   usage:  [-h] [--foo-bar FOO-BAR]

   optional arguments:
    -h, --help  show this help message and exit
    --foo-bar FOO-BAR


action
------

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

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

* "'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'" that respectively store the values "True" and
  "False" with default values of "False" and "True":

     >>> 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'" - This appends each argument value to a list. It is
  useful for allowing an option to be specified multiple times. If the
  default value is a non-empty list, the parsed value will start with
  the default list's elements and any values from the command line
  will be appended after those default values. Example usage:

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

* "'append_const'" - This appends the value specified by the const
  keyword argument to a list; note that the const keyword argument
  defaults to "None". The "'append_const'" action is typically useful
  when multiple arguments need to store constants to the same list.
  For example:

     >>> 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'>])

* "'extend'" - This appends each item from a multi-value argument to a
  list. The "'extend'" action is typically used with the nargs keyword
  argument value "'+'" or "'*'". Note that when nargs is "None" (the
  default) or "'?'", each character of the argument string will be
  appended 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'])

  Added in version 3.8.

* "'count'" - This counts the number of times an argument occurs. For
  example, this is useful for increasing verbosity levels:

     >>> 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

You may also specify an arbitrary action by passing an "Action"
subclass (e.g. "BooleanOptionalAction") or other object that
implements the same interface. Only actions that consume command-line
arguments (e.g. "'store'", "'append'", "'extend'", or custom actions
with non-zero "nargs") can be used with positional arguments.

The recommended way to create a custom action is to extend "Action",
overriding the "__call__()" method and optionally the "__init__()" and
"format_usage()" methods. You can also register custom actions using
the "register()" method and reference them by their registered name.

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

   >>> 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. See also 多義性のある引数の指定. 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='?')
     >>> parser.add_argument('outfile', nargs='?')
     >>> parser.parse_args(['input.txt', 'output.txt'])
     Namespace(infile='input.txt', outfile='output.txt')
     >>> parser.parse_args(['input.txt'])
     Namespace(infile='input.txt', outfile=None)
     >>> parser.parse_args([])
     Namespace(infile=None, outfile=None)

* "'*'" -- すべてのコマンドライン引数がリストに集められます。複数の位
  置引数が "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'])

* "'+'". Just like "'*'", all command-line arguments present are
  gathered into a list.  Additionally, an error message will be
  generated if there wasn't at least one command-line argument
  present.  For example:

     >>> 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. Actions that do not consume command-line
arguments (e.g. "'store_const'") set "nargs=0".


const
-----

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

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

* When "add_argument()" is called with option strings (like "-f" or "
  --foo") and "nargs='?'".  This creates an optional argument that can
  be followed by zero or one command-line arguments. When parsing the
  command line, if the option string is encountered with no command-
  line argument following it, the value from "const" will be used. See
  the nargs description for examples.

バージョン 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 overwrite 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)

For required arguments, the "default" value is ignored. For example,
this applies to positional arguments with nargs values other than "?"
or "*", or optional arguments marked as "required=True".

"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 a callable that accepts a single string
or the name of a registered type (see "register()") If the function
raises "ArgumentTypeError", "TypeError", or "ValueError", the
exception is caught and a nicely formatted error message is displayed.
Other exception types are not 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('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')

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

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

Note that *choices* are checked after any type conversions have been
performed, so objects in *choices* should match the type specified.
This can make *choices* appear unfamiliar in usage, help, or error
messages.

To keep *choices* user-friendly, consider a custom type wrapper that
converts and formats values, or omit type and handle conversion in
your application code.

ヘルプテキストにおいて整形された 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.

"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')


deprecated
----------

During a project's lifetime, some arguments may need to be removed
from the command line. Before removing them, you should inform your
users that the arguments are deprecated and will be removed. The
"deprecated" keyword argument of "add_argument()", which defaults to
"False", specifies if the argument is deprecated and will be removed
in the future. For arguments, if "deprecated" is "True", then a
warning will be printed to "sys.stderr" when the argument is used:

   >>> import argparse
   >>> parser = argparse.ArgumentParser(prog='snake.py')
   >>> parser.add_argument('--legs', default=0, type=int, deprecated=True)
   >>> parser.parse_args([])
   Namespace(legs=0)
   >>> parser.parse_args(['--legs', '4'])
   snake.py: warning: option '--legs' is deprecated
   Namespace(legs=4)

Added in version 3.13.


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__()".

   __call__(parser, namespace, values, option_string=None)

      "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".

   format_usage()

      "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.

class argparse.BooleanOptionalAction

   A subclass of "Action" for handling boolean flags with positive and
   negative options. Adding a single argument such as "--foo"
   automatically creates both "--foo" and "--no-foo" options, storing
   "True" and "False" respectively:

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

   Added in version 3.9.


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)

See also the argparse howto on ambiguous arguments for more details.


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

"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'


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


Subcommands
-----------

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

   Many programs split up their functionality into a number of
   subcommands, for example, the "svn" program can invoke subcommands
   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 subcommands 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 subcommand
     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 - name of the attribute under which subcommand name will be
     stored; by default "None" and no value is stored

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

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

   * metavar - string presenting available subcommands in help; by
     default it is "None" and presents subcommands 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='subcommand 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=('X', 'Y', 'Z'), 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}   subcommand 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')

   "add_parser()" supports also an additional *deprecated* argument,
   which allows to deprecate the subparser.

   >>> import argparse
   >>> parser = argparse.ArgumentParser(prog='chicken.py')
   >>> subparsers = parser.add_subparsers()
   >>> run = subparsers.add_parser('run')
   >>> fly = subparsers.add_parser('fly', deprecated=True)
   >>> parser.parse_args(['fly'])
   chicken.py: warning: command 'fly' is deprecated
   Namespace()

   Added in version 3.13.

   One particularly effective way of handling subcommands 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:

      >>> # subcommand 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-only parameter.

   バージョン 3.14 で変更: Subparser's *prog* is no longer affected by
   a custom usage message in the main parser.


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'>)

   注釈:

     If one argument uses *FileType* and then a subsequent argument
     fails, an error is reported but the file is not automatically
     closed. This can also clobber the output files. 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.

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

   バージョン 3.14 で非推奨.


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

ArgumentParser.add_argument_group(title=None, description=None, *[, argument_default][, conflict_handler])

   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

   The optional, keyword-only parameters argument_default and
   conflict_handler allow for finer-grained control of the behavior of
   the argument group. These parameters have the same meaning as in
   the "ArgumentParser" constructor, but apply specifically to the
   argument group rather than the entire parser.

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

   Deprecated since version 3.11, removed in version 3.14: Calling
   "add_argument_group()" on an argument group now raises an
   exception. This nesting was never supported, often failed to work
   correctly, and was unintentionally exposed through inheritance.

   バージョン 3.14 で非推奨: Passing prefix_chars to
   "add_argument_group()" is now deprecated.


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

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()". However, a mutually exclusive group can be
   added to an argument group that has a title and description. For
   example:

      >>> parser = argparse.ArgumentParser(prog='PROG')
      >>> group = parser.add_argument_group('Group title', 'Group description')
      >>> exclusive_group = group.add_mutually_exclusive_group(required=True)
      >>> exclusive_group.add_argument('--foo', help='foo help')
      >>> exclusive_group.add_argument('--bar', help='bar help')
      >>> parser.print_help()
      usage: PROG [-h] (--foo FOO | --bar BAR)

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

      Group title:
        Group description

        --foo FOO   foo help
        --bar BAR   bar help

   Deprecated since version 3.11, removed in version 3.14: Calling
   "add_argument_group()" or "add_mutually_exclusive_group()" on a
   mutually exclusive group now raises an exception. This nesting was
   never supported, often failed to work correctly, and was
   unintentionally exposed through inheritance.


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

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)

   Note that defaults can be set at both the parser level using
   "set_defaults()" and at the argument level using "add_argument()".
   If both are called for the same argument, the last default set for
   an argument is used:

      >>> 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)

   Sometimes a script only needs to handle a specific set of command-
   line arguments, leaving any unrecognized arguments for another
   script or program. In these cases, the "parse_known_args()" method
   can be useful.

   This method works similarly to "parse_args()", but it does not
   raise an error for extra, unrecognized arguments. Instead, it
   parses the known arguments and returns a two item tuple that
   contains the populated namespace and the list of any unrecognized
   arguments.

      >>> 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* to "sys.stderr"
   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
   "sys.stderr" 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()" は、解析されない引数が残された場合にはエ
   ラーを送出します。

   Added in version 3.7.


Registering custom types or actions
-----------------------------------

ArgumentParser.register(registry_name, value, object)

   Sometimes it's desirable to use a custom string in error messages
   to provide more user-friendly output. In these cases, "register()"
   can be used to register custom actions or types with a parser and
   allow you to reference the type by their registered name instead of
   their callable name.

   The "register()" method accepts three arguments - a
   *registry_name*, specifying the internal registry where the object
   will be stored (e.g., "action", "type"), *value*, which is the key
   under which the object will be registered, and object, the callable
   to be registered.

   The following example shows how to register a custom type with a
   parser:

      >>> import argparse
      >>> parser = argparse.ArgumentParser()
      >>> parser.register('type', 'hexadecimal integer', lambda s: int(s, 16))
      >>> parser.add_argument('--foo', type='hexadecimal integer')
      _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type='hexadecimal integer', choices=None, required=False, help=None, metavar=None, deprecated=False)
      >>> parser.parse_args(['--foo', '0xFA'])
      Namespace(foo=250)
      >>> parser.parse_args(['--foo', '1.2'])
      usage: PROG [-h] [--foo FOO]
      PROG: error: argument --foo: invalid 'hexadecimal integer' value: '1.2'


例外
====

exception argparse.ArgumentError

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

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

exception argparse.ArgumentTypeError

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

-[ ガイドとチュートリアル ]-

* Argparse チュートリアル

* Migrating "optparse" code to "argparse"
