# Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Python 3.14\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-04-15 00:29+0000\n" "PO-Revision-Date: 2018-05-23 14:38+0000\n" "Last-Translator: Adrian Liaw \n" "Language-Team: Chinese - TAIWAN (https://github.com/python/python-docs-zh-" "tw)\n" "Language: zh_TW\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../library/argparse.rst:2 msgid "" ":mod:`!argparse` --- Parser for command-line options, arguments and " "subcommands" msgstr ":mod:`!argparse` --- 命令列選項、引數和子命令的剖析器" #: ../../library/argparse.rst:12 msgid "**Source code:** :source:`Lib/argparse.py`" msgstr "**原始碼:**\\ :source:`Lib/argparse.py`" #: ../../library/argparse.rst:16 msgid "" "While :mod:`!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 :ref:`choosing-" "an-argument-parser` 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)." msgstr "" "雖然 :mod:`!argparse` 是實作基本命令列應用程式時預設推薦的標準函式庫模組,但" "如果開發者對命令列應用程式的行為有更精確的要求,可能會發現它無法提供足夠的控" "制程度。當 ``argparse`` 不支援應用程式所需的行為時(例如完全停用交錯選項與位" "置引數的支援,或是允許以 ``-`` 開頭但可能與其他已定義選項相同的選項參數值)," "請參閱\\ :ref:`choosing-an-argument-parser`\\ 以了解替代方案。" #: ../../library/argparse.rst:-1 msgid "Tutorial" msgstr "教學" #: ../../library/argparse.rst:30 msgid "" "This page contains the API reference information. For a more gentle " "introduction to Python command-line parsing, have a look at the :ref:" "`argparse tutorial `." msgstr "" "本頁包含 API 參考資訊。如需更淺顯的 Python 命令列剖析介紹,請參閱 :ref:" "`argparse 教學 `。" #: ../../library/argparse.rst:34 msgid "" "The :mod:`!argparse` module makes it easy to write user-friendly command-" "line interfaces. The program defines what arguments it requires, and :mod:`!" "argparse` will figure out how to parse those out of :data:`sys.argv`. The :" "mod:`!argparse` module also automatically generates help and usage " "messages. The module will also issue errors when users give the program " "invalid arguments." msgstr "" ":mod:`!argparse` 模組使得撰寫使用者友善的命令列介面變得容易。程式定義它需要什" "麼引數,而 :mod:`!argparse` 會找出如何從 :data:`sys.argv` 中剖析這些引數。:" "mod:`!argparse` 模組也會自動產生說明和用法訊息。當使用者向程式提供無效引數" "時,此模組也會發出錯誤。" #: ../../library/argparse.rst:40 msgid "" "The :mod:`!argparse` module's support for command-line interfaces is built " "around an instance of :class:`argparse.ArgumentParser`. It is a container " "for argument specifications and has options that apply to the parser as " "whole::" msgstr "" ":mod:`!argparse` 模組對命令列介面的支援是圍繞 :class:`argparse." "ArgumentParser` 的實例建構的。它是引數規格的容器,並具有適用於整個剖析器的選" "項: ::" #: ../../library/argparse.rst:44 msgid "" "parser = argparse.ArgumentParser(\n" " prog='ProgramName',\n" " description='What the program does',\n" " epilog='Text at the bottom of help')" msgstr "" "parser = argparse.ArgumentParser(\n" " prog='ProgramName',\n" " description='What the program does',\n" " epilog='Text at the bottom of help')" #: ../../library/argparse.rst:49 msgid "" "The :meth:`ArgumentParser.add_argument` method attaches individual argument " "specifications to the parser. It supports positional arguments, options " "that accept values, and on/off flags::" msgstr "" ":meth:`ArgumentParser.add_argument` 方法會將個別的引數規格附加到剖析器。它支" "援位置引數、接受值的選項以及開關旗標:::" #: ../../library/argparse.rst:53 msgid "" "parser.add_argument('filename') # positional argument\n" "parser.add_argument('-c', '--count') # option that takes a value\n" "parser.add_argument('-v', '--verbose',\n" " action='store_true') # on/off flag" msgstr "" "parser.add_argument('filename') # 位置引數\n" "parser.add_argument('-c', '--count') # 接收一個值的選項\n" "parser.add_argument('-v', '--verbose',\n" " action='store_true') # 開關旗標" #: ../../library/argparse.rst:58 msgid "" "The :meth:`ArgumentParser.parse_args` method runs the parser and places the " "extracted data in a :class:`argparse.Namespace` object::" msgstr "" ":meth:`ArgumentParser.parse_args` 方法會執行剖析器,並將擷取的資料放入一個 :" "class:`argparse.Namespace` 物件中:::" #: ../../library/argparse.rst:61 msgid "" "args = parser.parse_args()\n" "print(args.filename, args.count, args.verbose)" msgstr "" "args = parser.parse_args()\n" "print(args.filename, args.count, args.verbose)" #: ../../library/argparse.rst:65 msgid "" "If you're looking for a guide about how to upgrade :mod:`optparse` code to :" "mod:`!argparse`, see :ref:`Upgrading Optparse Code `." msgstr "" "如果你在尋找如何將 :mod:`optparse` 程式碼升級到 :mod:`!argparse` 的指南,請參" "閱\\ :ref:`升級 Optparse 程式碼 `。" #: ../../library/argparse.rst:69 msgid "ArgumentParser objects" msgstr "ArgumentParser 物件" #: ../../library/argparse.rst:79 msgid "" "Create a new :class:`ArgumentParser` object. All parameters should be passed " "as keyword arguments. Each parameter has its own more detailed description " "below, but in short they are:" msgstr "" "建立一個新的 :class:`ArgumentParser` 物件。所有參數都應該作為關鍵字引數傳入。" "每個參數在下面都有更詳細的描述,簡而言之它們是:" #: ../../library/argparse.rst:83 msgid "" "prog_ - The name of the program (default: generated from the ``__main__`` " "module attributes and ``sys.argv[0]``)" msgstr "" "prog_ - 程式的名稱(預設值:從 ``__main__`` 模組屬性和 ``sys.argv[0]`` 產生)" #: ../../library/argparse.rst:86 msgid "" "usage_ - The string describing the program usage (default: generated from " "arguments added to parser)" msgstr "usage_ - 描述程式用法的字串(預設值:從新增到剖析器的引數產生)" #: ../../library/argparse.rst:89 msgid "" "description_ - Text to display before the argument help (by default, no text)" msgstr "description_ - 引數說明之前要顯示的文字(預設值:無文字)" #: ../../library/argparse.rst:92 msgid "epilog_ - Text to display after the argument help (by default, no text)" msgstr "epilog_ - 引數說明之後要顯示的文字(預設值:無文字)" #: ../../library/argparse.rst:94 msgid "" "parents_ - A list of :class:`ArgumentParser` objects whose arguments should " "also be included" msgstr "parents_ - 一個 :class:`ArgumentParser` 物件的串列,其引數也應該被包含" #: ../../library/argparse.rst:97 msgid "formatter_class_ - A class for customizing the help output" msgstr "formatter_class_ - 用於自訂幫助說明輸出的類別" #: ../../library/argparse.rst:99 msgid "" "prefix_chars_ - The set of characters that prefix optional arguments " "(default: '-')" msgstr "prefix_chars_ - 前綴可選引數的字元集合(預設值:'-')" #: ../../library/argparse.rst:102 msgid "" "fromfile_prefix_chars_ - The set of characters that prefix files from which " "additional arguments should be read (default: ``None``)" msgstr "" "fromfile_prefix_chars_ - 前綴檔案的字元集合,額外引數將從這些檔案中讀取(預設" "值:``None``)" #: ../../library/argparse.rst:105 msgid "" "argument_default_ - The global default value for arguments (default: " "``None``)" msgstr "argument_default_ - 引數的全域預設值(預設值:``None``)" #: ../../library/argparse.rst:108 msgid "" "conflict_handler_ - The strategy for resolving conflicting optionals " "(usually unnecessary)" msgstr "conflict_handler_ - 解決衝突可選引數的策略(通常不需要)" #: ../../library/argparse.rst:111 msgid "" "add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)" msgstr "add_help_ - 加入一個 ``-h/--help`` 選項到剖析器(預設值:``True``)" #: ../../library/argparse.rst:113 msgid "" "allow_abbrev_ - Allows long options to be abbreviated if the abbreviation is " "unambiguous (default: ``True``)" msgstr "" "allow_abbrev_ - 允許長選項被縮寫,只要縮寫是無歧義的(預設值:``True``)" #: ../../library/argparse.rst:116 msgid "" "exit_on_error_ - Determines whether or not :class:`!ArgumentParser` exits " "with error info when an error occurs. (default: ``True``)" msgstr "" "exit_on_error_ - 決定 :class:`!ArgumentParser` 在發生錯誤時是否帶著錯誤資訊退" "出。(預設值:``True``)" #: ../../library/argparse.rst:119 msgid "" "suggest_on_error_ - Enables suggestions for mistyped argument choices and " "subparser names (default: ``False``)" msgstr "" "suggest_on_error_ - 啟用對拼錯的引數選擇和子剖析器名稱的建議(預設值:" "``False``)" #: ../../library/argparse.rst:122 msgid "color_ - Allow color output (default: ``True``)" msgstr "color_ - 允許彩色輸出(預設值:``True``)" #: ../../library/argparse.rst:124 msgid "*allow_abbrev* parameter was added." msgstr "新增 *allow_abbrev* 參數。" #: ../../library/argparse.rst:127 msgid "" "In previous versions, *allow_abbrev* also disabled grouping of short flags " "such as ``-vv`` to mean ``-v -v``." msgstr "" "在之前的版本中,*allow_abbrev* 也會停用短旗標的分組,例如以 ``-vv`` 表示 ``-" "v -v``。" #: ../../library/argparse.rst:131 msgid "*exit_on_error* parameter was added." msgstr "新增 *exit_on_error* 參數。" #: ../../library/argparse.rst:134 msgid "*suggest_on_error* and *color* parameters were added." msgstr "新增 *suggest_on_error* 和 *color* 參數。" #: ../../library/argparse.rst:137 ../../library/argparse.rst:696 msgid "The following sections describe how each of these are used." msgstr "以下各節描述了這些參數的使用方式。" #: ../../library/argparse.rst:143 msgid "prog" msgstr "prog" #: ../../library/argparse.rst:146 msgid "" "By default, :class:`ArgumentParser` calculates the name of the program to " "display in help messages depending on the way the Python interpreter was run:" msgstr "" "預設情況下,:class:`ArgumentParser` 會根據 Python 直譯器的執行方式計算要在說" "明訊息中顯示的程式名稱:" #: ../../library/argparse.rst:149 msgid "" "The :func:`base name ` of ``sys.argv[0]`` if a file was " "passed as argument." msgstr "" "如果傳入的引數是一個檔案,則使用 ``sys.argv[0]`` 的\\ :func:`基底名稱 `。" #: ../../library/argparse.rst:151 msgid "" "The Python interpreter name followed by ``sys.argv[0]`` if a directory or a " "zipfile was passed as argument." msgstr "" "如果傳入的引數是一個目錄或 zip 檔案,則使用 Python 直譯器名稱加上 ``sys." "argv[0]``。" #: ../../library/argparse.rst:153 msgid "" "The Python interpreter name followed by ``-m`` followed by the module or " "package name if the :option:`-m` option was used." msgstr "" "如果使用了 :option:`-m` 選項,則使用 Python 直譯器名稱加上 ``-m`` 再加上模組" "或套件名稱。" #: ../../library/argparse.rst:156 msgid "" "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 :class:`ArgumentParser`::" msgstr "" "這個預設值幾乎都不會錯,因為它會使說明訊息與命令列上呼叫程式時所用的字串一" "致。然而,若要更改此預設行為,可以使用 :class:`ArgumentParser` 的 ``prog=`` " "引數提供另一個值: ::" #: ../../library/argparse.rst:161 msgid "" ">>> parser = argparse.ArgumentParser(prog='myprogram')\n" ">>> parser.print_help()\n" "usage: myprogram [-h]\n" "\n" "options:\n" " -h, --help show this help message and exit" msgstr "" ">>> parser = argparse.ArgumentParser(prog='myprogram')\n" ">>> parser.print_help()\n" "usage: myprogram [-h]\n" "\n" "options:\n" " -h, --help show this help message and exit" #: ../../library/argparse.rst:168 msgid "" "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." msgstr "" "請注意,無論程式名稱是從 ``sys.argv[0]``、從 ``__main__`` 模組屬性還是從 " "``prog=`` 引數決定的,都可以在說明訊息中透過 ``%(prog)s`` 格式說明符號使用。" #: ../../library/argparse.rst:175 msgid "" ">>> parser = argparse.ArgumentParser(prog='myprogram')\n" ">>> parser.add_argument('--foo', help='foo of the %(prog)s program')\n" ">>> parser.print_help()\n" "usage: myprogram [-h] [--foo FOO]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo FOO foo of the myprogram program" msgstr "" ">>> parser = argparse.ArgumentParser(prog='myprogram')\n" ">>> parser.add_argument('--foo', help='foo of the %(prog)s program')\n" ">>> parser.print_help()\n" "usage: myprogram [-h] [--foo FOO]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo FOO foo of the myprogram program" #: ../../library/argparse.rst:184 msgid "" "The default ``prog`` value now reflects how ``__main__`` was actually " "executed, rather than always being ``os.path.basename(sys.argv[0])``." msgstr "" "預設的 ``prog`` 值現在會反映 ``__main__`` 實際的執行方式,而非總是使用 ``os." "path.basename(sys.argv[0])``。" #: ../../library/argparse.rst:189 msgid "usage" msgstr "usage" #: ../../library/argparse.rst:191 msgid "" "By default, :class:`ArgumentParser` calculates the usage message from the " "arguments it contains. The default message can be overridden with the " "``usage=`` keyword argument::" msgstr "" "預設情況下,:class:`ArgumentParser` 會根據它包含的引數計算出用法訊息。可以使" "用 ``usage=`` 關鍵字引數覆寫預設訊息: ::" #: ../../library/argparse.rst:195 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s " "[options]')\n" ">>> parser.add_argument('--foo', nargs='?', help='foo help')\n" ">>> parser.add_argument('bar', nargs='+', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [options]\n" "\n" "positional arguments:\n" " bar bar help\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo [FOO] foo help" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s " "[options]')\n" ">>> parser.add_argument('--foo', nargs='?', help='foo help')\n" ">>> parser.add_argument('bar', nargs='+', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [options]\n" "\n" "positional arguments:\n" " bar bar help\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo [FOO] foo help" #: ../../library/argparse.rst:208 msgid "" "The ``%(prog)s`` format specifier is available to fill in the program name " "in your usage messages." msgstr "``%(prog)s`` 格式說明符號可用於在你的用法訊息中填入程式名稱。" #: ../../library/argparse.rst:211 msgid "" "When a custom usage message is specified for the main parser, you may also " "want to consider passing the ``prog`` argument to :meth:`~ArgumentParser." "add_subparsers` or the ``prog`` and the ``usage`` arguments to :meth:" "`~_SubParsersAction.add_parser`, to ensure consistent command prefixes and " "usage information across subparsers." msgstr "" "當為主剖析器指定了自訂用法訊息時,你可能也會想考慮將 ``prog`` 引數傳給 :meth:" "`~ArgumentParser.add_subparsers`,或是將 ``prog`` 和 ``usage`` 引數傳給 :" "meth:`~_SubParsersAction.add_parser` 以確保子剖析器之間的命令前綴和用法資訊一" "致。" #: ../../library/argparse.rst:221 msgid "description" msgstr "description" #: ../../library/argparse.rst:223 msgid "" "Most calls to the :class:`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." msgstr "" "大多數對 :class:`ArgumentParser` 建構函式的呼叫會使用 ``description=`` 關鍵字" "引數。此引數提供程式功能和運作方式的簡短描述。在說明訊息中,這個描述會顯示在" "命令列用法字串和各引數的說明訊息之間。" #: ../../library/argparse.rst:229 msgid "" "By default, the description will be line-wrapped so that it fits within the " "given space. To change this behavior, see the formatter_class_ argument." msgstr "" "預設情況下,該描述會被自動斷行來配合給定的空間。若要更改此行為,請參閱 " "formatter_class_ 引數。" #: ../../library/argparse.rst:234 msgid "epilog" msgstr "epilog" #: ../../library/argparse.rst:236 msgid "" "Some programs like to display additional description of the program after " "the description of the arguments. Such text can be specified using the " "``epilog=`` argument to :class:`ArgumentParser`::" msgstr "" "有些程式喜歡在引數描述之後顯示程式的額外說明。可以使用 :class:" "`ArgumentParser` 的 ``epilog=`` 引數來指定這類文字: ::" #: ../../library/argparse.rst:240 msgid "" ">>> parser = argparse.ArgumentParser(\n" "... description='A foo that bars',\n" "... epilog=\"And that's how you'd foo a bar\")\n" ">>> parser.print_help()\n" "usage: argparse.py [-h]\n" "\n" "A foo that bars\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "And that's how you'd foo a bar" msgstr "" ">>> parser = argparse.ArgumentParser(\n" "... description='A foo that bars',\n" "... epilog=\"And that's how you'd foo a bar\")\n" ">>> parser.print_help()\n" "usage: argparse.py [-h]\n" "\n" "A foo that bars\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "And that's how you'd foo a bar" #: ../../library/argparse.rst:253 msgid "" "As with the description_ argument, the ``epilog=`` text is by default line-" "wrapped, but this behavior can be adjusted with the formatter_class_ " "argument to :class:`ArgumentParser`." msgstr "" "與 description_ 引數一樣,``epilog=`` 文字預設會被自動斷行,但可以透過 :" "class:`ArgumentParser` 的 formatter_class_ 引數調整此行為。" #: ../../library/argparse.rst:259 msgid "parents" msgstr "parents" #: ../../library/argparse.rst:261 msgid "" "Sometimes, several parsers share a common set of arguments. Rather than " "repeating the definitions of these arguments, a single parser with all the " "shared arguments and passed to ``parents=`` argument to :class:" "`ArgumentParser` can be used. The ``parents=`` argument takes a list of :" "class:`ArgumentParser` objects, collects all the positional and optional " "actions from them, and adds these actions to the :class:`ArgumentParser` " "object being constructed::" msgstr "" "有時候多個剖析器會共用一組共同的引數。與其重複定義這些引數,不如使用一個包含" "所有共用引數的剖析器,並將其傳給 :class:`ArgumentParser` 的 ``parents=`` 引" "數。``parents=`` 引數接受一個 :class:`ArgumentParser` 物件的串列,收集它們的" "所有位置 action 和可選 action,並將這些 action 加入正在建構的 :class:" "`ArgumentParser` 物件中: ::" #: ../../library/argparse.rst:268 msgid "" ">>> parent_parser = argparse.ArgumentParser(add_help=False)\n" ">>> parent_parser.add_argument('--parent', type=int)\n" "\n" ">>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])\n" ">>> foo_parser.add_argument('foo')\n" ">>> foo_parser.parse_args(['--parent', '2', 'XXX'])\n" "Namespace(foo='XXX', parent=2)\n" "\n" ">>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])\n" ">>> bar_parser.add_argument('--bar')\n" ">>> bar_parser.parse_args(['--bar', 'YYY'])\n" "Namespace(bar='YYY', parent=None)" msgstr "" ">>> parent_parser = argparse.ArgumentParser(add_help=False)\n" ">>> parent_parser.add_argument('--parent', type=int)\n" "\n" ">>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])\n" ">>> foo_parser.add_argument('foo')\n" ">>> foo_parser.parse_args(['--parent', '2', 'XXX'])\n" "Namespace(foo='XXX', parent=2)\n" "\n" ">>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])\n" ">>> bar_parser.add_argument('--bar')\n" ">>> bar_parser.parse_args(['--bar', 'YYY'])\n" "Namespace(bar='YYY', parent=None)" #: ../../library/argparse.rst:281 msgid "" "Note that most parent parsers will specify ``add_help=False``. Otherwise, " "the :class:`ArgumentParser` will see two ``-h/--help`` options (one in the " "parent and one in the child) and raise an error." msgstr "" "請注意,大多數父剖析器會指定 ``add_help=False``。否則 :class:" "`ArgumentParser` 會看到兩個 ``-h/--help`` 選項(一個在父剖析器中,一個在子剖" "析器中)並引發錯誤。" #: ../../library/argparse.rst:286 msgid "" "You must fully initialize the parsers before passing them via ``parents=``. " "If you change the parent parsers after the child parser, those changes will " "not be reflected in the child." msgstr "" "你必須在透過 ``parents=`` 傳入剖析器之前完全初始化它們。如果你在子剖析器之後" "更改父剖析器,那些更改將不會反映在子剖析器中。" #: ../../library/argparse.rst:294 msgid "formatter_class" msgstr "formatter_class" #: ../../library/argparse.rst:296 msgid "" ":class:`ArgumentParser` objects allow the help formatting to be customized " "by specifying an alternate formatting class. Currently, there are four such " "classes:" msgstr "" ":class:`ArgumentParser` 物件允許透過指定替代的格式化類別來自訂說明格式。目前" "有四個這樣的類別:" #: ../../library/argparse.rst:305 msgid "" ":class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give " "more control over how textual descriptions are displayed. By default, :class:" "`ArgumentParser` objects line-wrap the description_ and epilog_ texts in " "command-line help messages::" msgstr "" ":class:`RawDescriptionHelpFormatter` 和 :class:`RawTextHelpFormatter` 提供了" "對文字描述顯示方式的更多控制。預設情況下,:class:`ArgumentParser` 物件會在命" "令列說明訊息中為 description_ 和 epilog_ 文字自動斷行: ::" #: ../../library/argparse.rst:310 msgid "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... description='''this description\n" "... was indented weird\n" "... but that is okay''',\n" "... epilog='''\n" "... likewise for this epilog whose whitespace will\n" "... be cleaned up and whose words will be wrapped\n" "... across a couple lines''')\n" ">>> parser.print_help()\n" "usage: PROG [-h]\n" "\n" "this description was indented weird but that is okay\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "likewise for this epilog whose whitespace will be cleaned up and whose " "words\n" "will be wrapped across a couple lines" msgstr "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... description='''this description\n" "... was indented weird\n" "... but that is okay''',\n" "... epilog='''\n" "... likewise for this epilog whose whitespace will\n" "... be cleaned up and whose words will be wrapped\n" "... across a couple lines''')\n" ">>> parser.print_help()\n" "usage: PROG [-h]\n" "\n" "this description was indented weird but that is okay\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "likewise for this epilog whose whitespace will be cleaned up and whose " "words\n" "will be wrapped across a couple lines" #: ../../library/argparse.rst:330 msgid "" "Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=`` " "indicates that description_ and epilog_ are already correctly formatted and " "should not be line-wrapped::" msgstr "" "將 :class:`RawDescriptionHelpFormatter` 作為 ``formatter_class=`` 傳入,表示 " "description_ 和 epilog_ 已經正確格式化,不應自動斷行: ::" #: ../../library/argparse.rst:334 msgid "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... formatter_class=argparse.RawDescriptionHelpFormatter,\n" "... description=textwrap.dedent('''\\\n" "... Please do not mess up this text!\n" "... --------------------------------\n" "... I have indented it\n" "... exactly the way\n" "... I want it\n" "... '''))\n" ">>> parser.print_help()\n" "usage: PROG [-h]\n" "\n" "Please do not mess up this text!\n" "--------------------------------\n" " I have indented it\n" " exactly the way\n" " I want it\n" "\n" "options:\n" " -h, --help show this help message and exit" msgstr "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... formatter_class=argparse.RawDescriptionHelpFormatter,\n" "... description=textwrap.dedent('''\\\n" "... Please do not mess up this text!\n" "... --------------------------------\n" "... I have indented it\n" "... exactly the way\n" "... I want it\n" "... '''))\n" ">>> parser.print_help()\n" "usage: PROG [-h]\n" "\n" "Please do not mess up this text!\n" "--------------------------------\n" " I have indented it\n" " exactly the way\n" " I want it\n" "\n" "options:\n" " -h, --help show this help message and exit" #: ../../library/argparse.rst:356 msgid "" ":class:`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." msgstr "" ":class:`RawTextHelpFormatter` 會為所有種類的說明文字保留空白,包括引數描述。" "然而多個換行符號會被替換為一個。如果你希望保留多個空白行,請在換行符號之間加" "入空格。" #: ../../library/argparse.rst:361 msgid "" ":class:`ArgumentDefaultsHelpFormatter` automatically adds information about " "default values to each of the argument help messages::" msgstr "" ":class:`ArgumentDefaultsHelpFormatter` 會自動將預設值的資訊加入每個引數的說明" "訊息中: ::" #: ../../library/argparse.rst:364 msgid "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n" ">>> parser.add_argument('--foo', type=int, default=42, help='FOO!')\n" ">>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')\n" ">>> parser.print_help()\n" "usage: PROG [-h] [--foo FOO] [bar ...]\n" "\n" "positional arguments:\n" " bar BAR! (default: [1, 2, 3])\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo FOO FOO! (default: 42)" msgstr "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n" ">>> parser.add_argument('--foo', type=int, default=42, help='FOO!')\n" ">>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')\n" ">>> parser.print_help()\n" "usage: PROG [-h] [--foo FOO] [bar ...]\n" "\n" "positional arguments:\n" " bar BAR! (default: [1, 2, 3])\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo FOO FOO! (default: 42)" #: ../../library/argparse.rst:379 msgid "" ":class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for " "each argument as the display name for its values (rather than using the " "dest_ as the regular formatter does)::" msgstr "" ":class:`MetavarTypeHelpFormatter` 使用每個引數的 type_ 引數名稱作為其值的顯示" "名稱(而非像一般格式化器使用 dest_): ::" #: ../../library/argparse.rst:383 msgid "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... formatter_class=argparse.MetavarTypeHelpFormatter)\n" ">>> parser.add_argument('--foo', type=int)\n" ">>> parser.add_argument('bar', type=float)\n" ">>> parser.print_help()\n" "usage: PROG [-h] [--foo int] float\n" "\n" "positional arguments:\n" " float\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo int" msgstr "" ">>> parser = argparse.ArgumentParser(\n" "... prog='PROG',\n" "... formatter_class=argparse.MetavarTypeHelpFormatter)\n" ">>> parser.add_argument('--foo', type=int)\n" ">>> parser.add_argument('bar', type=float)\n" ">>> parser.print_help()\n" "usage: PROG [-h] [--foo int] float\n" "\n" "positional arguments:\n" " float\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo int" #: ../../library/argparse.rst:400 msgid "prefix_chars" msgstr "prefix_chars" #: ../../library/argparse.rst:402 msgid "" "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 :class:`ArgumentParser` constructor::" msgstr "" "大多數命令列選項會使用 ``-`` 作為前綴,例如 ``-f/--foo``。需要支援不同或額外" "前綴字元的剖析器,例如 ``+f`` 或 ``/foo`` 之類的選項,可以使用 :class:" "`ArgumentParser` 建構函式的 ``prefix_chars=`` 引數來指定: ::" #: ../../library/argparse.rst:408 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')\n" ">>> parser.add_argument('+f')\n" ">>> parser.add_argument('++bar')\n" ">>> parser.parse_args('+f X ++bar Y'.split())\n" "Namespace(bar='Y', f='X')" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')\n" ">>> parser.add_argument('+f')\n" ">>> parser.add_argument('++bar')\n" ">>> parser.parse_args('+f X ++bar Y'.split())\n" "Namespace(bar='Y', f='X')" #: ../../library/argparse.rst:414 msgid "" "The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of " "characters that does not include ``-`` will cause ``-f/--foo`` options to be " "disallowed." msgstr "" "``prefix_chars=`` 引數預設值為 ``'-'``。提供一個不包含 ``-`` 的字元集合會導" "致 ``-f/--foo`` 選項被禁止。" #: ../../library/argparse.rst:420 msgid "fromfile_prefix_chars" msgstr "fromfile_prefix_chars" #: ../../library/argparse.rst:422 msgid "" "Sometimes, when dealing with a particularly long argument list, it may make " "sense to keep the list of arguments in a file rather than typing it out at " "the command line. If the ``fromfile_prefix_chars=`` argument is given to " "the :class:`ArgumentParser` constructor, then arguments that start with any " "of the specified characters will be treated as files, and will be replaced " "by the arguments they contain. For example::" msgstr "" "當處理特別長的引數串列時,有時候將引數串列保存在檔案中可能比在命令列上逐一輸" "入更合理。如果將 ``fromfile_prefix_chars=`` 引數傳給 :class:`ArgumentParser` " "建構函式,那麼剖析器會將以任何指定字元開頭的引數視為檔案,並以檔案包含的引數" "取代之。例如: ::" #: ../../library/argparse.rst:429 msgid "" ">>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:\n" "... fp.write('-f\\nbar')\n" "...\n" ">>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n" ">>> parser.add_argument('-f')\n" ">>> parser.parse_args(['-f', 'foo', '@args.txt'])\n" "Namespace(f='bar')" msgstr "" ">>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:\n" "... fp.write('-f\\nbar')\n" "...\n" ">>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n" ">>> parser.add_argument('-f')\n" ">>> parser.parse_args(['-f', 'foo', '@args.txt'])\n" "Namespace(f='bar')" #: ../../library/argparse.rst:437 msgid "" "Arguments read from a file must be one per line by default (but see also :" "meth:`~ArgumentParser.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']``." msgstr "" "從檔案讀取的引數預設必須每行一個(但也請參閱 :meth:`~ArgumentParser." "convert_arg_line_to_args`),且剖析器會將其視為與命令列上引用檔案的原始引數位" "於相同位置。因此在上面的範例中,運算式 ``['-f', 'foo', '@args.txt']`` 等同於" "運算式 ``['-f', 'foo', '-f', 'bar']``。" #: ../../library/argparse.rst:445 msgid "" "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." msgstr "" "空行會被視為空字串 (``''``),可以作為值但不能作為引數。若空行被讀取為引數,會" "導致 \"unrecognized arguments\" 錯誤。" #: ../../library/argparse.rst:449 msgid "" ":class:`ArgumentParser` uses :term:`filesystem encoding and error handler` " "to read the file containing arguments." msgstr "" ":class:`ArgumentParser` 使用\\ :term:`檔案系統編碼和錯誤處理函式 `\\ 來讀取包含引數的檔案。" #: ../../library/argparse.rst:452 msgid "" "The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that " "arguments will never be treated as file references." msgstr "" "``fromfile_prefix_chars=`` 引數預設值為 ``None``,意味著引數永遠不會被視為檔" "案參照。" #: ../../library/argparse.rst:455 msgid "" ":class:`ArgumentParser` changed encoding and errors to read arguments files " "from default (e.g. :func:`locale.getpreferredencoding(False) ` and ``\"strict\"``) to the :term:`filesystem encoding " "and error handler`. Arguments file should be encoded in UTF-8 instead of " "ANSI Codepage on Windows." msgstr "" ":class:`ArgumentParser` 將讀取引數檔案的編碼和錯誤處理從預設值(例如 :func:" "`locale.getpreferredencoding(False) ` 和 " "``\"strict\"``)改為\\ :term:`檔案系統編碼和錯誤處理函式 `。在 Windows 上引數檔案應使用 UTF-8 而非 ANSI 字" "碼頁編碼。" #: ../../library/argparse.rst:463 msgid "argument_default" msgstr "argument_default" #: ../../library/argparse.rst:465 msgid "" "Generally, argument defaults are specified either by passing a default to :" "meth:`~ArgumentParser.add_argument` or by calling the :meth:`~ArgumentParser." "set_defaults` methods with a specific set of name-value pairs. Sometimes " "however, it may be useful to specify a single parser-wide default for " "arguments. This can be accomplished by passing the ``argument_default=`` " "keyword argument to :class:`ArgumentParser`. For example, to globally " "suppress attribute creation on :meth:`~ArgumentParser.parse_args` calls, we " "supply ``argument_default=SUPPRESS``::" msgstr "" "一般而言,引數預設值可以透過將預設值傳給 :meth:`~ArgumentParser." "add_argument` 或是透過呼叫 :meth:`~ArgumentParser.set_defaults` 方法並指定一" "組名稱—值對 (name-value pair) 來設定。然而有時候為引數指定一個剖析器層級的單" "一預設值可能很有用。這可以透過將 ``argument_default=`` 關鍵字引數傳給 :class:" "`ArgumentParser` 來完成。例如若要全域地抑制 :meth:`~ArgumentParser." "parse_args` 呼叫時的屬性建立,我們可以提供 ``argument_default=SUPPRESS``: ::" #: ../../library/argparse.rst:474 msgid "" ">>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n" ">>> parser.add_argument('--foo')\n" ">>> parser.add_argument('bar', nargs='?')\n" ">>> parser.parse_args(['--foo', '1', 'BAR'])\n" "Namespace(bar='BAR', foo='1')\n" ">>> parser.parse_args([])\n" "Namespace()" msgstr "" ">>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n" ">>> parser.add_argument('--foo')\n" ">>> parser.add_argument('bar', nargs='?')\n" ">>> parser.parse_args(['--foo', '1', 'BAR'])\n" "Namespace(bar='BAR', foo='1')\n" ">>> parser.parse_args([])\n" "Namespace()" #: ../../library/argparse.rst:485 msgid "allow_abbrev" msgstr "allow_abbrev" #: ../../library/argparse.rst:487 msgid "" "Normally, when you pass an argument list to the :meth:`~ArgumentParser." "parse_args` method of an :class:`ArgumentParser`, it :ref:`recognizes " "abbreviations ` of long options." msgstr "" "當你將引數串列傳給 :class:`ArgumentParser` 的 :meth:`~ArgumentParser." "parse_args` 方法時,它會通常會\\ :ref:`辨識為長選項的縮寫 `。" #: ../../library/argparse.rst:491 msgid "This feature can be disabled by setting ``allow_abbrev`` to ``False``::" msgstr "可以透過將 ``allow_abbrev`` 設為 ``False`` 來停用此功能: ::" #: ../../library/argparse.rst:493 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)\n" ">>> parser.add_argument('--foobar', action='store_true')\n" ">>> parser.add_argument('--foonley', action='store_false')\n" ">>> parser.parse_args(['--foon'])\n" "usage: PROG [-h] [--foobar] [--foonley]\n" "PROG: error: unrecognized arguments: --foon" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)\n" ">>> parser.add_argument('--foobar', action='store_true')\n" ">>> parser.add_argument('--foonley', action='store_false')\n" ">>> parser.parse_args(['--foon'])\n" "usage: PROG [-h] [--foobar] [--foonley]\n" "PROG: error: unrecognized arguments: --foon" #: ../../library/argparse.rst:504 msgid "conflict_handler" msgstr "conflict_handler" #: ../../library/argparse.rst:506 msgid "" ":class:`ArgumentParser` objects do not allow two actions with the same " "option string. By default, :class:`ArgumentParser` objects raise an " "exception if an attempt is made to create an argument with an option string " "that is already in use::" msgstr "" ":class:`ArgumentParser` 物件不允許兩個 action 擁有相同的選項字串。預設情況" "下,如果嘗試建立一個使用已存在選項字串的引數,:class:`ArgumentParser` 物件會" "引發例外: ::" #: ../../library/argparse.rst:511 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-f', '--foo', help='old foo help')\n" ">>> parser.add_argument('--foo', help='new foo help')\n" "Traceback (most recent call last):\n" " ..\n" "ArgumentError: argument --foo: conflicting option string(s): --foo" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-f', '--foo', help='old foo help')\n" ">>> parser.add_argument('--foo', help='new foo help')\n" "Traceback (most recent call last):\n" " ..\n" "ArgumentError: argument --foo: conflicting option string(s): --foo" #: ../../library/argparse.rst:518 msgid "" "Sometimes (e.g. when using parents_) it may be useful to simply override any " "older arguments with the same option string. To get this behavior, the " "value ``'resolve'`` can be supplied to the ``conflict_handler=`` argument " "of :class:`ArgumentParser`::" msgstr "" "有時候(例如使用 parents_ 時)直接覆寫具有相同選項字串的舊引數可能很有用。若" "要得到此行為,可以將值 ``'resolve'`` 提供給 :class:`ArgumentParser` 的 " "``conflict_handler=`` 引數: ::" #: ../../library/argparse.rst:523 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', " "conflict_handler='resolve')\n" ">>> parser.add_argument('-f', '--foo', help='old foo help')\n" ">>> parser.add_argument('--foo', help='new foo help')\n" ">>> parser.print_help()\n" "usage: PROG [-h] [-f FOO] [--foo FOO]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " -f FOO old foo help\n" " --foo FOO new foo help" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', " "conflict_handler='resolve')\n" ">>> parser.add_argument('-f', '--foo', help='old foo help')\n" ">>> parser.add_argument('--foo', help='new foo help')\n" ">>> parser.print_help()\n" "usage: PROG [-h] [-f FOO] [--foo FOO]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " -f FOO old foo help\n" " --foo FOO new foo help" #: ../../library/argparse.rst:534 msgid "" "Note that :class:`ArgumentParser` objects only remove an action if all of " "its option strings are overridden. So, in the example above, the old ``-f/--" "foo`` action is retained as the ``-f`` action, because only the ``--foo`` " "option string was overridden." msgstr "" "請注意,只有當一個 action 的所有選項字串都被覆寫時,:class:`ArgumentParser` " "物件才會移除該 action。因此在上面的範例中,舊的 ``-f/--foo`` action 會保留為 " "``-f`` action,因為只有 ``--foo`` 選項字串被覆寫。" #: ../../library/argparse.rst:541 msgid "add_help" msgstr "add_help" #: ../../library/argparse.rst:543 msgid "" "By default, :class:`ArgumentParser` objects add an option which simply " "displays the parser's help message. If ``-h`` or ``--help`` is supplied at " "the command line, the :class:`!ArgumentParser` help will be printed." msgstr "" "預設情況下,:class:`ArgumentParser` 物件會加入一個選項來簡單地顯示剖析器的說" "明訊息。如果在命令列上提供了 ``-h`` 或 ``--help``,將會印出 :class:`!" "ArgumentParser` 的說明。" #: ../../library/argparse.rst:547 msgid "" "Occasionally, it may be useful to disable the addition of this help option. " "This can be achieved by passing ``False`` as the ``add_help=`` argument to :" "class:`ArgumentParser`::" msgstr "" "停用自動加入的幫助說明選項 (help option) 有時可能很有用。可以透過將 " "``False`` 作為 ``add_help=`` 引數傳給 :class:`ArgumentParser` 來達成: ::" #: ../../library/argparse.rst:551 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" ">>> parser.add_argument('--foo', help='foo help')\n" ">>> parser.print_help()\n" "usage: PROG [--foo FOO]\n" "\n" "options:\n" " --foo FOO foo help" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" ">>> parser.add_argument('--foo', help='foo help')\n" ">>> parser.print_help()\n" "usage: PROG [--foo FOO]\n" "\n" "options:\n" " --foo FOO foo help" #: ../../library/argparse.rst:559 msgid "" "The help option is typically ``-h/--help``. The exception to this is if the " "``prefix_chars=`` is specified and does not include ``-``, in which case ``-" "h`` and ``--help`` are not valid options. In this case, the first character " "in ``prefix_chars`` is used to prefix the help options::" msgstr "" "幫助說明選項通常是 ``-h/--help``。例外情況是如果指定了 ``prefix_chars=`` 且不" "包含 ``-``,此時 ``-h`` 和 ``--help`` 不是有效的選項。在這種情況下," "``prefix_chars`` 中的第一個字元會用作幫助說明選項的前綴: ::" #: ../../library/argparse.rst:565 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')\n" ">>> parser.print_help()\n" "usage: PROG [+h]\n" "\n" "options:\n" " +h, ++help show this help message and exit" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')\n" ">>> parser.print_help()\n" "usage: PROG [+h]\n" "\n" "options:\n" " +h, ++help show this help message and exit" #: ../../library/argparse.rst:574 msgid "exit_on_error" msgstr "exit_on_error" #: ../../library/argparse.rst:576 msgid "" "Normally, when you pass an invalid argument list to the :meth:" "`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`, it will " "print a *message* to :data:`sys.stderr` and exit with a status code of 2." msgstr "" "當你將無效的引數串列傳給 :class:`ArgumentParser` 的 :meth:`~ArgumentParser." "parse_args` 方法時,它通常會向 :data:`sys.stderr` 印出一個\\ *訊息*\\ 並以狀" "態碼 2 退出。" #: ../../library/argparse.rst:580 msgid "" "If the user would like to catch errors manually, the feature can be enabled " "by setting ``exit_on_error`` to ``False``::" msgstr "" "如果使用者想要手動捕捉錯誤,可以透過將 ``exit_on_error`` 設為 ``False`` 來啟" "用此功能: ::" #: ../../library/argparse.rst:583 msgid "" ">>> parser = argparse.ArgumentParser(exit_on_error=False)\n" ">>> parser.add_argument('--integers', type=int)\n" "_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, " "const=None, default=None, type=, choices=None, help=None, " "metavar=None)\n" ">>> try:\n" "... parser.parse_args('--integers a'.split())\n" "... except argparse.ArgumentError:\n" "... print('Catching an argumentError')\n" "...\n" "Catching an argumentError" msgstr "" ">>> parser = argparse.ArgumentParser(exit_on_error=False)\n" ">>> parser.add_argument('--integers', type=int)\n" "_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, " "const=None, default=None, type=, choices=None, help=None, " "metavar=None)\n" ">>> try:\n" "... parser.parse_args('--integers a'.split())\n" "... except argparse.ArgumentError:\n" "... print('Catching an argumentError')\n" "...\n" "Catching an argumentError" #: ../../library/argparse.rst:596 msgid "suggest_on_error" msgstr "suggest_on_error" #: ../../library/argparse.rst:598 msgid "" "By default, when a user passes an invalid argument choice or subparser " "name, :class:`ArgumentParser` will exit with error info and list the " "permissible argument choices (if specified) or subparser names as part of " "the error message." msgstr "" "預設情況下,當使用者傳入無效的引數選擇或子剖析器名稱時,:class:" "`ArgumentParser` 會帶著錯誤資訊退出,並將允許的引數選擇(如果有指定的話)或子" "剖析器名稱列為錯誤訊息的一部分。" #: ../../library/argparse.rst:602 msgid "" "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::" msgstr "" "如果使用者想要啟用對拼錯的引數選擇和子剖析器名稱的建議,可以透過將 " "``suggest_on_error`` 設為 ``True`` 來啟用此功能。請注意,這僅適用於指定的選擇" "皆為字串的引數: ::" #: ../../library/argparse.rst:607 msgid "" ">>> parser = argparse.ArgumentParser(suggest_on_error=True)\n" ">>> parser.add_argument('--action', choices=['debug', 'dryrun'])\n" ">>> parser.parse_args(['--action', 'debugg'])\n" "usage: tester.py [-h] [--action {debug,dryrun}]\n" "tester.py: error: argument --action: invalid choice: 'debugg', maybe you " "meant 'debug'? (choose from debug, dryrun)" msgstr "" ">>> parser = argparse.ArgumentParser(suggest_on_error=True)\n" ">>> parser.add_argument('--action', choices=['debug', 'dryrun'])\n" ">>> parser.parse_args(['--action', 'debugg'])\n" "usage: tester.py [-h] [--action {debug,dryrun}]\n" "tester.py: error: argument --action: invalid choice: 'debugg', maybe you " "meant 'debug'? (choose from debug, dryrun)" #: ../../library/argparse.rst:613 msgid "" "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::" msgstr "" "如果你正在撰寫需要與舊版 Python 相容的程式碼,並且想要在 " "``suggest_on_error`` 可用時伺機使用它,你可以在初始化剖析器後將其設為屬性,而" "非使用關鍵字引數: ::" #: ../../library/argparse.rst:618 msgid "" ">>> parser = argparse.ArgumentParser(description='Process some integers.')\n" ">>> parser.suggest_on_error = True" msgstr "" ">>> parser = argparse.ArgumentParser(description='Process some integers.')\n" ">>> parser.suggest_on_error = True" #: ../../library/argparse.rst:625 msgid "color" msgstr "color" #: ../../library/argparse.rst:627 msgid "" "By default, the help message is printed in color using `ANSI escape " "sequences `__. If you want " "plain text help messages, you can disable this :ref:`in your local " "environment `, or in the argument parser itself " "by setting ``color`` to ``False``::" msgstr "" "預設情況下,說明訊息會使用 `ANSI 跳脫序列 `__\\ 以彩色印出。如果你想要純文字說明訊息,可以\\ :ref:`在" "你的本地環境中 `\\ 停用它,或是透過將 ``color`` " "設為 ``False`` 在引數剖析器本身停用: ::" #: ../../library/argparse.rst:633 msgid "" ">>> parser = argparse.ArgumentParser(description='Process some integers.',\n" "... color=False)\n" ">>> parser.add_argument('--action', choices=['sum', 'max'])\n" ">>> parser.add_argument('integers', metavar='N', type=int, nargs='+',\n" "... help='an integer for the accumulator')\n" ">>> parser.parse_args(['--help'])" msgstr "" ">>> parser = argparse.ArgumentParser(description='Process some integers.',\n" "... color=False)\n" ">>> parser.add_argument('--action', choices=['sum', 'max'])\n" ">>> parser.add_argument('integers', metavar='N', type=int, nargs='+',\n" "... help='an integer for the accumulator')\n" ">>> parser.parse_args(['--help'])" #: ../../library/argparse.rst:640 msgid "" "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." msgstr "" "請注意,當 ``color=True`` 時,彩色輸出取決於環境變數和終端機能力。然而,如果 " "``color=False``,即使設定了 ``FORCE_COLOR`` 之類的環境變數,彩色輸出也是會被" "停用。" #: ../../library/argparse.rst:647 msgid "" "Error messages will include color codes when redirecting stderr to a file. " "To avoid this, set the |NO_COLOR|_ or :envvar:`PYTHON_COLORS` environment " "variable (for example, ``NO_COLOR=1 python script.py 2> errors.txt``)." msgstr "" "將 stderr 重新導向到檔案時,錯誤訊息會包含顏色代碼。若要避免此情況,請設定 |" "NO_COLOR|_ 或 :envvar:`PYTHON_COLORS` 環境變數(例如 ``NO_COLOR=1 python " "script.py 2> errors.txt``)。" #: ../../library/argparse.rst:656 msgid "The add_argument() method" msgstr "add_argument() 方法" #: ../../library/argparse.rst:662 msgid "" "Define how a single command-line argument should be parsed. Each parameter " "has its own more detailed description below, but in short they are:" msgstr "" "定義單個命令列引數應如何被剖析。每個參數在下面都有更詳細的描述,簡而言之它們" "是:" #: ../../library/argparse.rst:665 msgid "" "`name or flags`_ - Either a name or a list of option strings, e.g. ``'foo'`` " "or ``'-f', '--foo'``." msgstr "" "`name or flags`_ - 一個名稱或選項字串的串列,例如 ``'foo'`` 或 ``'-f', '--" "foo'``。" #: ../../library/argparse.rst:668 msgid "" "action_ - The basic type of action to be taken when this argument is " "encountered at the command line." msgstr "action_ - 在命令列遇到此引數時要執行的基本 action 類型。" #: ../../library/argparse.rst:671 msgid "nargs_ - The number of command-line arguments that should be consumed." msgstr "nargs_ - 應消耗的命令列引數數量。" #: ../../library/argparse.rst:673 msgid "" "const_ - A constant value required by some action_ and nargs_ selections." msgstr "const_ - 某些 action_ 和 nargs_ 選擇所需的常數值。" #: ../../library/argparse.rst:675 msgid "" "default_ - The value produced if the argument is absent from the command " "line and if it is absent from the namespace object." msgstr "default_ - 如果引數不在命令列中且不在命名空間物件中時所產生的值。" #: ../../library/argparse.rst:678 msgid "" "type_ - The type to which the command-line argument should be converted." msgstr "type_ - 命令列引數應轉換成的型別。" #: ../../library/argparse.rst:680 msgid "choices_ - A sequence of the allowable values for the argument." msgstr "choices_ - 引數允許值的序列。" #: ../../library/argparse.rst:682 msgid "" "required_ - Whether or not the command-line option may be omitted (optionals " "only)." msgstr "required_ - 命令列選項是否可省略(僅限可選引數)。" #: ../../library/argparse.rst:685 msgid "help_ - A brief description of what the argument does." msgstr "help_ - 引數功能的簡短描述。" #: ../../library/argparse.rst:687 msgid "metavar_ - A name for the argument in usage messages." msgstr "metavar_ - 引數在用法訊息中的名稱。" #: ../../library/argparse.rst:689 msgid "" "dest_ - The name of the attribute to be added to the object returned by :" "meth:`parse_args`." msgstr "dest_ - 要加入到 :meth:`parse_args` 回傳物件中的屬性名稱。" #: ../../library/argparse.rst:692 msgid "deprecated_ - Whether or not use of the argument is deprecated." msgstr "deprecated_ - 引數的使用是否已被棄用。" #: ../../library/argparse.rst:694 msgid "The method returns an :class:`Action` object representing the argument." msgstr "" #: ../../library/argparse.rst:702 msgid "name or flags" msgstr "name or flags" #: ../../library/argparse.rst:704 msgid "" "The :meth:`~ArgumentParser.add_argument` method must know whether an " "optional argument, like ``-f`` or ``--foo``, or a positional argument, like " "a list of filenames, is expected. The first arguments passed to :meth:" "`~ArgumentParser.add_argument` must therefore be either a series of flags, " "or a simple argument name." msgstr "" ":meth:`~ArgumentParser.add_argument` 方法必須知道預期的是可選引數(如 ``-f`` " "或 ``--foo``)還是位置引數(如檔案名稱的串列)。因此,傳給 :meth:" "`~ArgumentParser.add_argument` 的第一個引數必須是一系列旗標或一個簡單的引數名" "稱。" #: ../../library/argparse.rst:710 msgid "For example, an optional argument could be created like::" msgstr "例如,可選引數可以像這樣建立: ::" #: ../../library/argparse.rst:712 msgid ">>> parser.add_argument('-f', '--foo')" msgstr ">>> parser.add_argument('-f', '--foo')" #: ../../library/argparse.rst:714 msgid "while a positional argument could be created like::" msgstr "而位置引數可以像這樣建立: ::" #: ../../library/argparse.rst:716 msgid ">>> parser.add_argument('bar')" msgstr ">>> parser.add_argument('bar')" #: ../../library/argparse.rst:718 msgid "" "When :meth:`~ArgumentParser.parse_args` is called, optional arguments will " "be identified by the ``-`` prefix, and the remaining arguments will be " "assumed to be positional::" msgstr "" "當呼叫 :meth:`~ArgumentParser.parse_args` 時,可選引數會透過 ``-`` 前綴來辨" "識,其餘的引數則假設為位置引數: ::" #: ../../library/argparse.rst:722 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-f', '--foo')\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_args(['BAR'])\n" "Namespace(bar='BAR', foo=None)\n" ">>> parser.parse_args(['BAR', '--foo', 'FOO'])\n" "Namespace(bar='BAR', foo='FOO')\n" ">>> parser.parse_args(['--foo', 'FOO'])\n" "usage: PROG [-h] [-f FOO] bar\n" "PROG: error: the following arguments are required: bar" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-f', '--foo')\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_args(['BAR'])\n" "Namespace(bar='BAR', foo=None)\n" ">>> parser.parse_args(['BAR', '--foo', 'FOO'])\n" "Namespace(bar='BAR', foo='FOO')\n" ">>> parser.parse_args(['--foo', 'FOO'])\n" "usage: PROG [-h] [-f FOO] bar\n" "PROG: error: the following arguments are required: bar" #: ../../library/argparse.rst:733 msgid "" "By default, :mod:`!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. For optional arguments, the dest_ parameter defaults to " "the argument name, with underscores ``_`` replacing hyphens ``-``. The " "metavar_ parameter defaults to the upper-cased name. For example::" msgstr "" "預設情況下,:mod:`!argparse` 會自動處理引數的內部命名和顯示名稱,簡化流程而不" "需要額外設定。因此,你不需要指定 dest_ 和 metavar_ 參數。對於可選的引數," "dest_ 參數預設為引數名稱,以底線 ``_`` 取代連字號 ``-``。metavar_ 參數預設為" "大寫的名稱。例如: ::" #: ../../library/argparse.rst:741 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--foo-bar')\n" ">>> parser.parse_args(['--foo-bar', 'FOO-BAR'])\n" "Namespace(foo_bar='FOO-BAR')\n" ">>> parser.print_help()\n" "usage: [-h] [--foo-bar FOO-BAR]\n" "\n" "optional arguments:\n" " -h, --help show this help message and exit\n" " --foo-bar FOO-BAR" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--foo-bar')\n" ">>> parser.parse_args(['--foo-bar', 'FOO-BAR'])\n" "Namespace(foo_bar='FOO-BAR')\n" ">>> parser.print_help()\n" "usage: [-h] [--foo-bar FOO-BAR]\n" "\n" "optional arguments:\n" " -h, --help show this help message and exit\n" " --foo-bar FOO-BAR" #: ../../library/argparse.rst:756 msgid "action" msgstr "action" #: ../../library/argparse.rst:758 msgid "" ":class:`ArgumentParser` objects associate command-line arguments with " "actions. These actions can do just about anything with the command-line " "arguments associated with them, though most actions simply add an attribute " "to the object returned by :meth:`~ArgumentParser.parse_args`. The " "``action`` keyword argument specifies how the command-line arguments should " "be handled. The supplied actions are:" msgstr "" ":class:`ArgumentParser` 物件會將命令列引數與 action 關聯起來。這些 action 幾" "乎可以對與其關聯的命令列引數做任何事情,但大多數 action 只是將屬性加入到 :" "meth:`~ArgumentParser.parse_args` 回傳的物件中。``action`` 關鍵字引數指定命令" "列引數應如何被處理。提供的 action 有:" #: ../../library/argparse.rst:764 msgid "" "``'store'`` - This just stores the argument's value. This is the default " "action." msgstr "``'store'`` - 這只是儲存引數的值。這是預設的 action。" #: ../../library/argparse.rst:767 msgid "" "``'store_const'`` - This stores the value specified by the const_ keyword " "argument; note that the const_ keyword argument defaults to ``None``. The " "``'store_const'`` action is most commonly used with optional arguments that " "specify some sort of flag. For example::" msgstr "" "``'store_const'`` - 這會儲存 const_ 關鍵字引數指定的值;請注意 const_ 關鍵字" "引數預設為 ``None``。``'store_const'`` action 最常與指定某種旗標的可選引數一" "起使用。例如: ::" #: ../../library/argparse.rst:772 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='store_const', const=42)\n" ">>> parser.parse_args(['--foo'])\n" "Namespace(foo=42)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='store_const', const=42)\n" ">>> parser.parse_args(['--foo'])\n" "Namespace(foo=42)" #: ../../library/argparse.rst:777 msgid "" "``'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``::" msgstr "" "``'store_true'`` 和 ``'store_false'`` - 這些是 ``'store_const'`` 的特殊情況," "分別儲存值 ``True`` 和 ``False``,預設值為 ``False`` 和 ``True``: ::" #: ../../library/argparse.rst:782 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='store_true')\n" ">>> parser.add_argument('--bar', action='store_false')\n" ">>> parser.add_argument('--baz', action='store_false')\n" ">>> parser.parse_args('--foo --bar'.split())\n" "Namespace(foo=True, bar=False, baz=True)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='store_true')\n" ">>> parser.add_argument('--bar', action='store_false')\n" ">>> parser.add_argument('--baz', action='store_false')\n" ">>> parser.parse_args('--foo --bar'.split())\n" "Namespace(foo=True, bar=False, baz=True)" #: ../../library/argparse.rst:789 msgid "" "``'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::" msgstr "" "``'append'`` - 這會將每個引數值附加到一個串列中。這對於允許一個選項被多次指定" "很有用。如果預設值是一個非空的串列,剖析後的值會以預設串列的元素開始,命令列" "的任何值則會附加在那些預設值之後。使用範例: ::" #: ../../library/argparse.rst:795 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='append', default=['0'])\n" ">>> parser.parse_args('--foo 1 --foo 2'.split())\n" "Namespace(foo=['0', '1', '2'])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='append', default=['0'])\n" ">>> parser.parse_args('--foo 1 --foo 2'.split())\n" "Namespace(foo=['0', '1', '2'])" #: ../../library/argparse.rst:800 msgid "" "``'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::" msgstr "" "``'append_const'`` - 這會將 const_ 關鍵字引數指定的值附加到一個串列中;請注" "意 const_ 關鍵字引數預設為 ``None``。``'append_const'`` action 通常在多個引數" "需要將常數儲存到同一個串列時很有用。例如: ::" #: ../../library/argparse.rst:806 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--str', dest='types', action='append_const', " "const=str)\n" ">>> parser.add_argument('--int', dest='types', action='append_const', " "const=int)\n" ">>> parser.parse_args('--str --int'.split())\n" "Namespace(types=[, ])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--str', dest='types', action='append_const', " "const=str)\n" ">>> parser.add_argument('--int', dest='types', action='append_const', " "const=int)\n" ">>> parser.parse_args('--str --int'.split())\n" "Namespace(types=[, ])" #: ../../library/argparse.rst:812 msgid "" "``'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::" msgstr "" "``'extend'`` - 這會將多值引數的每個項目附加到一個串列中。``'extend'`` action " "通常與 nargs_ 關鍵字引數值 ``'+'`` 或 ``'*'`` 一起使用。請注意,當 nargs_ 為 " "``None``\\ (預設值)或 ``'?'`` 時,引數字串的每個字元都會被附加到串列中。使" "用範例: ::" #: ../../library/argparse.rst:820 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument(\"--foo\", action=\"extend\", nargs=\"+\", " "type=str)\n" ">>> parser.parse_args([\"--foo\", \"f1\", \"--foo\", \"f2\", \"f3\", " "\"f4\"])\n" "Namespace(foo=['f1', 'f2', 'f3', 'f4'])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument(\"--foo\", action=\"extend\", nargs=\"+\", " "type=str)\n" ">>> parser.parse_args([\"--foo\", \"f1\", \"--foo\", \"f2\", \"f3\", " "\"f4\"])\n" "Namespace(foo=['f1', 'f2', 'f3', 'f4'])" #: ../../library/argparse.rst:827 msgid "" "``'count'`` - This counts the number of times an argument occurs. For " "example, this is useful for increasing verbosity levels::" msgstr "" "``'count'`` - 這會計算引數出現的次數。例如,這對於增加詳細程度等級很有用: ::" #: ../../library/argparse.rst:830 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--verbose', '-v', action='count', default=0)\n" ">>> parser.parse_args(['-vvv'])\n" "Namespace(verbose=3)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--verbose', '-v', action='count', default=0)\n" ">>> parser.parse_args(['-vvv'])\n" "Namespace(verbose=3)" #: ../../library/argparse.rst:835 msgid "Note, the *default* will be ``None`` unless explicitly set to *0*." msgstr "請注意,除非明確設為 *0*,否則 *default* 將為 ``None``。" #: ../../library/argparse.rst:837 msgid "" "``'help'`` - This prints a complete help message for all the options in the " "current parser and then exits. By default a help action is automatically " "added to the parser. See :class:`ArgumentParser` for details of how the " "output is created." msgstr "" "``'help'`` - 這會印出目前剖析器中所有選項的完整說明訊息,然後退出。預設情況" "下,help action 會自動加入到剖析器。有關輸出如何建立的詳情,請參閱 :class:" "`ArgumentParser`。" #: ../../library/argparse.rst:842 msgid "" "``'version'`` - This expects a ``version=`` keyword argument in the :meth:" "`~ArgumentParser.add_argument` call, and prints version information and " "exits when invoked::" msgstr "" "``'version'`` - 這預期在 :meth:`~ArgumentParser.add_argument` 呼叫中有一個 " "``version=`` 關鍵字引數,並在被呼叫時印出版本資訊並退出: ::" #: ../../library/argparse.rst:846 msgid "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--version', action='version', version='%(prog)s " "2.0')\n" ">>> parser.parse_args(['--version'])\n" "PROG 2.0" msgstr "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--version', action='version', version='%(prog)s " "2.0')\n" ">>> parser.parse_args(['--version'])\n" "PROG 2.0" #: ../../library/argparse.rst:852 msgid "" "You may also specify an arbitrary action by passing an :class:`Action` " "subclass (e.g. :class:`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." msgstr "" "你也可以傳遞一個 :class:`Action` 子類別(例如 :class:" "`BooleanOptionalAction`)或實作相同介面的其他物件。只有會消耗命令列引數的 " "action(例如 ``'store'``、``'append'``、``'extend'`` 或 ``nargs`` 不為零的自" "訂 action)可用於位置引數。" #: ../../library/argparse.rst:858 msgid "" "The recommended way to create a custom action is to extend :class:`Action`, " "overriding the :meth:`!__call__` method and optionally the :meth:`!__init__` " "and :meth:`!format_usage` methods. You can also register custom actions " "using the :meth:`~ArgumentParser.register` method and reference them by " "their registered name." msgstr "" "建立自訂 action 的建議方式是擴充 :class:`Action`,覆寫 :meth:`!__call__` 方" "法,並選擇性地覆寫 :meth:`!__init__` 和 :meth:`!format_usage` 方法。你也可以" "使用 :meth:`~ArgumentParser.register` 方法註冊自訂 action,並透過它們的註冊名" "稱來參照。" #: ../../library/argparse.rst:863 msgid "An example of a custom action::" msgstr "自訂 action 的範例: ::" #: ../../library/argparse.rst:865 msgid "" ">>> class FooAction(argparse.Action):\n" "... def __init__(self, option_strings, dest, nargs=None, **kwargs):\n" "... if nargs is not None:\n" "... raise ValueError(\"nargs not allowed\")\n" "... super().__init__(option_strings, dest, **kwargs)\n" "... def __call__(self, parser, namespace, values, option_string=None):\n" "... print('%r %r %r' % (namespace, values, option_string))\n" "... setattr(namespace, self.dest, values)\n" "...\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action=FooAction)\n" ">>> parser.add_argument('bar', action=FooAction)\n" ">>> args = parser.parse_args('1 --foo 2'.split())\n" "Namespace(bar=None, foo=None) '1' None\n" "Namespace(bar='1', foo=None) '2' '--foo'\n" ">>> args\n" "Namespace(bar='1', foo='2')" msgstr "" ">>> class FooAction(argparse.Action):\n" "... def __init__(self, option_strings, dest, nargs=None, **kwargs):\n" "... if nargs is not None:\n" "... raise ValueError(\"nargs not allowed\")\n" "... super().__init__(option_strings, dest, **kwargs)\n" "... def __call__(self, parser, namespace, values, option_string=None):\n" "... print('%r %r %r' % (namespace, values, option_string))\n" "... setattr(namespace, self.dest, values)\n" "...\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action=FooAction)\n" ">>> parser.add_argument('bar', action=FooAction)\n" ">>> args = parser.parse_args('1 --foo 2'.split())\n" "Namespace(bar=None, foo=None) '1' None\n" "Namespace(bar='1', foo=None) '2' '--foo'\n" ">>> args\n" "Namespace(bar='1', foo='2')" #: ../../library/argparse.rst:883 msgid "For more details, see :class:`Action`." msgstr "更多詳情請見 :class:`Action`。" #: ../../library/argparse.rst:889 msgid "nargs" msgstr "nargs" #: ../../library/argparse.rst:891 msgid "" ":class:`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 :ref:`specifying-ambiguous-arguments`. The supported values " "are:" msgstr "" ":class:`ArgumentParser` 物件通常將單個命令列引數與單個要執行的 action 關聯起" "來。``nargs`` 關鍵字引數會將不同數量的命令列引數與單個 action 關聯。另請參閱" "\\ :ref:`specifying-ambiguous-arguments`。支援的值有:" #: ../../library/argparse.rst:896 msgid "" "``N`` (an integer). ``N`` arguments from the command line will be gathered " "together into a list. For example::" msgstr "" "``N``\\ (一個整數)。命令列中的 ``N`` 個引數會被收集到一個串列中。例如: ::" #: ../../library/argparse.rst:899 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', nargs=2)\n" ">>> parser.add_argument('bar', nargs=1)\n" ">>> parser.parse_args('c --foo a b'.split())\n" "Namespace(bar=['c'], foo=['a', 'b'])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', nargs=2)\n" ">>> parser.add_argument('bar', nargs=1)\n" ">>> parser.parse_args('c --foo a b'.split())\n" "Namespace(bar=['c'], foo=['a', 'b'])" #: ../../library/argparse.rst:905 msgid "" "Note that ``nargs=1`` produces a list of one item. This is different from " "the default, in which the item is produced by itself." msgstr "" "請注意 ``nargs=1`` 會產生一個只有一個項目的串列。這與預設情況不同,預設情況下" "項目會單獨產生。" #: ../../library/argparse.rst:910 msgid "" "``'?'``. One argument will be consumed from the command line if possible, " "and produced as a single item. If no command-line argument is present, the " "value from default_ will be produced. Note that for optional arguments, " "there is an additional case - the option string is present but not followed " "by a command-line argument. In this case the value from const_ will be " "produced. Some examples to illustrate this::" msgstr "" "``'?'``。如果可能的話,會從命令列消耗一個引數,並作為單個項目產生。如果沒有命" "令列引數存在,會產生 default_ 的值。請注意,對於可選引數有一個額外的情況 —— " "選項字串存在但後面沒有跟著命令列引數,在這種情況下會產生 const_ 的值。以下是" "這個情況的範例: ::" #: ../../library/argparse.rst:917 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', nargs='?', const='c', default='d')\n" ">>> parser.add_argument('bar', nargs='?', default='d')\n" ">>> parser.parse_args(['XX', '--foo', 'YY'])\n" "Namespace(bar='XX', foo='YY')\n" ">>> parser.parse_args(['XX', '--foo'])\n" "Namespace(bar='XX', foo='c')\n" ">>> parser.parse_args([])\n" "Namespace(bar='d', foo='d')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', nargs='?', const='c', default='d')\n" ">>> parser.add_argument('bar', nargs='?', default='d')\n" ">>> parser.parse_args(['XX', '--foo', 'YY'])\n" "Namespace(bar='XX', foo='YY')\n" ">>> parser.parse_args(['XX', '--foo'])\n" "Namespace(bar='XX', foo='c')\n" ">>> parser.parse_args([])\n" "Namespace(bar='d', foo='d')" #: ../../library/argparse.rst:927 msgid "" "One of the more common uses of ``nargs='?'`` is to allow optional input and " "output files::" msgstr "``nargs='?'`` 比較常見的用途之一是允許可選的輸入和輸出檔案: ::" #: ../../library/argparse.rst:930 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('infile', nargs='?')\n" ">>> parser.add_argument('outfile', nargs='?')\n" ">>> parser.parse_args(['input.txt', 'output.txt'])\n" "Namespace(infile='input.txt', outfile='output.txt')\n" ">>> parser.parse_args(['input.txt'])\n" "Namespace(infile='input.txt', outfile=None)\n" ">>> parser.parse_args([])\n" "Namespace(infile=None, outfile=None)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('infile', nargs='?')\n" ">>> parser.add_argument('outfile', nargs='?')\n" ">>> parser.parse_args(['input.txt', 'output.txt'])\n" "Namespace(infile='input.txt', outfile='output.txt')\n" ">>> parser.parse_args(['input.txt'])\n" "Namespace(infile='input.txt', outfile=None)\n" ">>> parser.parse_args([])\n" "Namespace(infile=None, outfile=None)" #: ../../library/argparse.rst:942 msgid "" "``'*'``. All command-line arguments present are gathered into a list. Note " "that it generally doesn't make much sense to have more than one positional " "argument with ``nargs='*'``, but multiple optional arguments with " "``nargs='*'`` is possible. For example::" msgstr "" "``'*'``。所有存在的命令列引數都會被收集到一個串列中。請注意,有多個 " "``nargs='*'`` 的位置引數通常沒有太大意義,但多個 ``nargs='*'`` 的可選引數是可" "能的。例如: ::" #: ../../library/argparse.rst:947 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', nargs='*')\n" ">>> parser.add_argument('--bar', nargs='*')\n" ">>> parser.add_argument('baz', nargs='*')\n" ">>> parser.parse_args('a b --foo x y --bar 1 2'.split())\n" "Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', nargs='*')\n" ">>> parser.add_argument('--bar', nargs='*')\n" ">>> parser.add_argument('baz', nargs='*')\n" ">>> parser.parse_args('a b --foo x y --bar 1 2'.split())\n" "Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])" #: ../../library/argparse.rst:956 msgid "" "``'+'``. 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::" msgstr "" "``'+'``。與 ``'*'`` 一樣,所有存在的命令列引數都會被收集到一個串列中。此外," "如果沒有至少一個命令列引數存在就會產生一個錯誤訊息。例如: ::" #: ../../library/argparse.rst:960 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('foo', nargs='+')\n" ">>> parser.parse_args(['a', 'b'])\n" "Namespace(foo=['a', 'b'])\n" ">>> parser.parse_args([])\n" "usage: PROG [-h] foo [foo ...]\n" "PROG: error: the following arguments are required: foo" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('foo', nargs='+')\n" ">>> parser.parse_args(['a', 'b'])\n" "Namespace(foo=['a', 'b'])\n" ">>> parser.parse_args([])\n" "usage: PROG [-h] foo [foo ...]\n" "PROG: error: the following arguments are required: foo" #: ../../library/argparse.rst:968 msgid "" "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``." msgstr "" "如果未提供 ``nargs`` 關鍵字引數,消耗的引數數量由 action_ 決定。一般而言,這" "意味著會消耗單個命令列引數並產生單個項目(而非串列)。不消耗命令列引數的 " "action(例如 ``'store_const'``)會設定 ``nargs=0``。" #: ../../library/argparse.rst:978 msgid "const" msgstr "const" #: ../../library/argparse.rst:980 msgid "" "The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to " "hold constant values that are not read from the command line but are " "required for the various :class:`ArgumentParser` actions. The two most " "common uses of it are:" msgstr "" ":meth:`~ArgumentParser.add_argument` 的 ``const`` 引數用於保存不從命令列讀取" "但為各種 :class:`ArgumentParser` action 所需的常數值。它最常見的兩種用途是:" #: ../../library/argparse.rst:984 msgid "" "When :meth:`~ArgumentParser.add_argument` is called with " "``action='store_const'`` or ``action='append_const'``. These actions add " "the ``const`` value to one of the attributes of the object returned by :meth:" "`~ArgumentParser.parse_args`. See the action_ description for examples. If " "``const`` is not provided to :meth:`~ArgumentParser.add_argument`, it will " "receive a default value of ``None``." msgstr "" "當 :meth:`~ArgumentParser.add_argument` 以 ``action='store_const'`` 或 " "``action='append_const'`` 呼叫時。這些 action 會將 ``const`` 值加入到 :meth:" "`~ArgumentParser.parse_args` 回傳物件的其中一個屬性中。範例請參閱 action_ 描" "述。如果未向 :meth:`~ArgumentParser.add_argument` 提供 ``const``,它會接收預" "設值 ``None``。" #: ../../library/argparse.rst:992 msgid "" "When :meth:`~ArgumentParser.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." msgstr "" "當 :meth:`~ArgumentParser.add_argument` 以選項字串(如 ``-f`` 或 ``--foo``)" "和 ``nargs='?'`` 呼叫時。這會建立一個可選引數,後面可以跟著零個或一個命令列引" "數。剖析命令列時,如果遇到選項字串但後面沒有命令列引數,會使用 ``const`` 的" "值。範例請參閱 nargs_ 描述。" #: ../../library/argparse.rst:999 msgid "" "``const=None`` by default, including when ``action='append_const'`` or " "``action='store_const'``." msgstr "" "``const=None`` 為預設值,包括當 ``action='append_const'`` 或 " "``action='store_const'`` 時。" #: ../../library/argparse.rst:1006 msgid "default" msgstr "default" #: ../../library/argparse.rst:1008 msgid "" "All optional arguments and some positional arguments may be omitted at the " "command line. The ``default`` keyword argument of :meth:`~ArgumentParser." "add_argument`, whose value defaults to ``None``, specifies what value should " "be used if the command-line argument is not present. For optional arguments, " "the ``default`` value is used when the option string was not present at the " "command line::" msgstr "" "所有可選引數和部分位置引數都可以在命令列上被省略。:meth:`~ArgumentParser." "add_argument` 的 ``default`` 關鍵字引數(其值預設為 ``None``)指定在命令列引" "數不存在時應使用的值。對於可選引數,當選項字串不在命令列上時會使用 " "``default`` 值: ::" #: ../../library/argparse.rst:1015 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default=42)\n" ">>> parser.parse_args(['--foo', '2'])\n" "Namespace(foo='2')\n" ">>> parser.parse_args([])\n" "Namespace(foo=42)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default=42)\n" ">>> parser.parse_args(['--foo', '2'])\n" "Namespace(foo='2')\n" ">>> parser.parse_args([])\n" "Namespace(foo=42)" #: ../../library/argparse.rst:1022 msgid "" "If the target namespace already has an attribute set, the action *default* " "will not overwrite it::" msgstr "" "如果目標命名空間已經設定了一個屬性,action 的 *default* 不會覆寫它: ::" #: ../../library/argparse.rst:1025 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default=42)\n" ">>> parser.parse_args([], namespace=argparse.Namespace(foo=101))\n" "Namespace(foo=101)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default=42)\n" ">>> parser.parse_args([], namespace=argparse.Namespace(foo=101))\n" "Namespace(foo=101)" #: ../../library/argparse.rst:1030 msgid "" "If the ``default`` value is a string, the parser parses the value as if it " "were a command-line argument. In particular, the parser applies any type_ " "conversion argument, if provided, before setting the attribute on the :class:" "`Namespace` return value. Otherwise, the parser uses the value as is::" msgstr "" "如果 ``default`` 值是一個字串,剖析器會像剖析命令列引數一樣剖析該值。特別是如" "果有提供 type_ 轉換引數,剖析器會在設定 :class:`Namespace` 回傳值的屬性之前先" "套用它。否則剖析器會直接使用該值: ::" #: ../../library/argparse.rst:1035 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--length', default='10', type=int)\n" ">>> parser.add_argument('--width', default=10.5, type=int)\n" ">>> parser.parse_args()\n" "Namespace(length=10, width=10.5)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--length', default='10', type=int)\n" ">>> parser.add_argument('--width', default=10.5, type=int)\n" ">>> parser.parse_args()\n" "Namespace(length=10, width=10.5)" #: ../../library/argparse.rst:1041 msgid "" "For positional arguments with nargs_ equal to ``?`` or ``*``, the " "``default`` value is used when no command-line argument was present::" msgstr "" "對於 nargs_ 等於 ``?`` 或 ``*`` 的位置引數,當沒有命令列引數存在時會使用 " "``default`` 值: ::" #: ../../library/argparse.rst:1044 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('foo', nargs='?', default=42)\n" ">>> parser.parse_args(['a'])\n" "Namespace(foo='a')\n" ">>> parser.parse_args([])\n" "Namespace(foo=42)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('foo', nargs='?', default=42)\n" ">>> parser.parse_args(['a'])\n" "Namespace(foo='a')\n" ">>> parser.parse_args([])\n" "Namespace(foo=42)" #: ../../library/argparse.rst:1051 msgid "" "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``." msgstr "" "對於 required_ 引數,``default`` 值會被忽略。例如,這適用於 nargs_ 值不是 ``?" "`` 或 ``*`` 的位置引數,或是標記為 ``required=True`` 的可選引數。" #: ../../library/argparse.rst:1055 msgid "" "Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if " "the command-line argument was not present::" msgstr "" "若有提供 ``default=argparse.SUPPRESS``,命令列引數不存在時就不會加入任何屬" "性: ::" #: ../../library/argparse.rst:1058 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default=argparse.SUPPRESS)\n" ">>> parser.parse_args([])\n" "Namespace()\n" ">>> parser.parse_args(['--foo', '1'])\n" "Namespace(foo='1')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default=argparse.SUPPRESS)\n" ">>> parser.parse_args([])\n" "Namespace()\n" ">>> parser.parse_args(['--foo', '1'])\n" "Namespace(foo='1')" #: ../../library/argparse.rst:1069 msgid "type" msgstr "type" #: ../../library/argparse.rst:1071 msgid "" "By default, the parser reads command-line arguments in as simple strings. " "However, quite often the command-line string should instead be interpreted " "as another type, such as a :class:`float` or :class:`int`. The ``type`` " "keyword for :meth:`~ArgumentParser.add_argument` allows any necessary type-" "checking and type conversions to be performed." msgstr "" "預設情況下,剖析器將命令列引數作為簡單字串讀取。然而命令列字串往往應直譯為另" "一種型別,例如 :class:`float` 或 :class:`int`。:meth:`~ArgumentParser." "add_argument` 的 ``type`` 關鍵字允許執行任何必要的型別檢查和型別轉換。" #: ../../library/argparse.rst:1077 msgid "" "If the type_ keyword is used with the default_ keyword, the type converter " "is only applied if the default is a string." msgstr "" "如果 type_ 關鍵字與 default_ 關鍵字一起使用,型別轉換器只會在預設值為字串時套" "用。" #: ../../library/argparse.rst:1080 msgid "" "The argument to ``type`` can be a callable that accepts a single string or " "the name of a registered type (see :meth:`~ArgumentParser.register`) If the " "function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or :exc:" "`ValueError`, the exception is caught and a nicely formatted error message " "is displayed. Other exception types are not handled." msgstr "" "``type`` 的引數可以是一個接受單個字串的可呼叫物件,或是已註冊型別的名稱(請參" "閱 :meth:`~ArgumentParser.register`)。如果函式引發 :exc:" "`ArgumentTypeError`、:exc:`TypeError` 或 :exc:`ValueError`,剖析器會捕捉例外" "並顯示格式良好的錯誤訊息。其他例外型別則不處理。" #: ../../library/argparse.rst:1086 msgid "Common built-in types and functions can be used as type converters:" msgstr "常見的內建型別和函式可以作為型別轉換器使用:" #: ../../library/argparse.rst:1088 msgid "" "import argparse\n" "import pathlib\n" "\n" "parser = argparse.ArgumentParser()\n" "parser.add_argument('count', type=int)\n" "parser.add_argument('distance', type=float)\n" "parser.add_argument('street', type=ascii)\n" "parser.add_argument('code_point', type=ord)\n" "parser.add_argument('datapath', type=pathlib.Path)" msgstr "" "import argparse\n" "import pathlib\n" "\n" "parser = argparse.ArgumentParser()\n" "parser.add_argument('count', type=int)\n" "parser.add_argument('distance', type=float)\n" "parser.add_argument('street', type=ascii)\n" "parser.add_argument('code_point', type=ord)\n" "parser.add_argument('datapath', type=pathlib.Path)" #: ../../library/argparse.rst:1100 msgid "User defined functions can be used as well:" msgstr "也可以用那些使用者定義的函式:" #: ../../library/argparse.rst:1102 msgid "" ">>> def hyphenated(string):\n" "... return '-'.join([word[:4] for word in string.casefold().split()])\n" "...\n" ">>> parser = argparse.ArgumentParser()\n" ">>> _ = parser.add_argument('short_title', type=hyphenated)\n" ">>> parser.parse_args(['\"The Tale of Two Cities\"'])\n" "Namespace(short_title='\"the-tale-of-two-citi')" msgstr "" ">>> def hyphenated(string):\n" "... return '-'.join([word[:4] for word in string.casefold().split()])\n" "...\n" ">>> parser = argparse.ArgumentParser()\n" ">>> _ = parser.add_argument('short_title', type=hyphenated)\n" ">>> parser.parse_args(['\"The Tale of Two Cities\"'])\n" "Namespace(short_title='\"the-tale-of-two-citi')" #: ../../library/argparse.rst:1112 msgid "" "The :func:`bool` function is not recommended as a type converter. All it " "does is convert empty strings to ``False`` and non-empty strings to " "``True``. This is usually not what is desired::" msgstr "" "不建議使用 :func:`bool` 函式作為型別轉換器。它所做的只是將空字串轉為 " "``False``,將非空字串轉為 ``True``。這通常不是期望的行為::" #: ../../library/argparse.rst:1116 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> _ = parser.add_argument('--verbose', type=bool)\n" ">>> parser.parse_args(['--verbose', 'False'])\n" "Namespace(verbose=True)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> _ = parser.add_argument('--verbose', type=bool)\n" ">>> parser.parse_args(['--verbose', 'False'])\n" "Namespace(verbose=True)" #: ../../library/argparse.rst:1121 msgid "" "See :class:`BooleanOptionalAction` or ``action='store_true'`` for common " "alternatives." msgstr "" #: ../../library/argparse.rst:1124 msgid "" "In general, the ``type`` keyword is a convenience that should only be used " "for simple conversions that can only raise one of the three supported " "exceptions. Anything with more interesting error-handling or resource " "management should be done downstream after the arguments are parsed." msgstr "" "一般而言,``type`` 關鍵字是一個便利功能,應只用於只會引發三種支援的例外之一的" "簡單轉換。任何更複雜的錯誤處理或資源管理都應在引數剖析之後的下游進行。" #: ../../library/argparse.rst:1129 msgid "" "For example, JSON or YAML conversions have complex error cases that require " "better reporting than can be given by the ``type`` keyword. A :exc:`~json." "JSONDecodeError` would not be well formatted and a :exc:`FileNotFoundError` " "exception would not be handled at all." msgstr "" "例如,JSON 或 YAML 轉換具有複雜的錯誤情況,需要比 ``type`` 關鍵字所能提供的更" "好的報告。:exc:`~json.JSONDecodeError` 無法得到良好的格式化,而 :exc:" "`FileNotFoundError` 例外則完全不會處理。" #: ../../library/argparse.rst:1134 msgid "" "Even :class:`~argparse.FileType` has its limitations for use with the " "``type`` keyword. If one argument uses :class:`~argparse.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 :keyword:`with`-statement to manage the " "files." msgstr "" "即使是 :class:`~argparse.FileType` 在與 ``type`` 關鍵字一起使用時也有其限制。" "如果一個引數使用了 :class:`~argparse.FileType`,然後後續的引數失敗了,雖然會" "報告錯誤但檔案不會自動關閉。在這種情況下,最好等到剖析器執行完畢後,再使用 :" "keyword:`with` 陳述式來管理檔案。" #: ../../library/argparse.rst:1141 msgid "" "For type checkers that simply check against a fixed set of values, consider " "using the choices_ keyword instead." msgstr "對於僅檢查固定值集合的型別檢查器,請考慮改用 choices_ 關鍵字。" #: ../../library/argparse.rst:1148 msgid "choices" msgstr "choices" #: ../../library/argparse.rst:1150 msgid "" "Some command-line arguments should be selected from a restricted set of " "values. These can be handled by passing a sequence object as the *choices* " "keyword argument to :meth:`~ArgumentParser.add_argument`. When the command " "line is parsed, argument values will be checked, and an error message will " "be displayed if the argument was not one of the acceptable values::" msgstr "" "某些命令列引數應從一組受限的值中選擇。這可以透過將序列物件作為 *choices* 關鍵" "字引數傳給 :meth:`~ArgumentParser.add_argument` 來處理。剖析命令列時會檢查引" "數值,如果引數不是可接受的值之一,就會顯示錯誤訊息: ::" #: ../../library/argparse.rst:1156 msgid "" ">>> parser = argparse.ArgumentParser(prog='game.py')\n" ">>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])\n" ">>> parser.parse_args(['rock'])\n" "Namespace(move='rock')\n" ">>> parser.parse_args(['fire'])\n" "usage: game.py [-h] {rock,paper,scissors}\n" "game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',\n" "'paper', 'scissors')" msgstr "" ">>> parser = argparse.ArgumentParser(prog='game.py')\n" ">>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])\n" ">>> parser.parse_args(['rock'])\n" "Namespace(move='rock')\n" ">>> parser.parse_args(['fire'])\n" "usage: game.py [-h] {rock,paper,scissors}\n" "game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',\n" "'paper', 'scissors')" #: ../../library/argparse.rst:1165 msgid "" "Any sequence can be passed as the *choices* value, so :class:`list` " "objects, :class:`tuple` objects, and custom sequences are all supported." msgstr "" "任何序列都可以作為 *choices* 值傳入,因此 :class:`list` 物件、:class:`tuple` " "物件和自訂序列都有被支援。" #: ../../library/argparse.rst:1168 msgid "" "Use of :class:`enum.Enum` is not recommended because it is difficult to " "control its appearance in usage, help, and error messages." msgstr "" "不建議使用 :class:`enum.Enum`,因為很難控制它在用法、說明和錯誤訊息中的長相。" #: ../../library/argparse.rst:1171 msgid "" "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." msgstr "" "請注意,*choices* 是在任何 type_ 轉換執行之後才被檢查的,因此 *choices* 中的" "物件應符合指定的 type_。這可能使 *choices* 在用法、說明或錯誤訊息中的長相看起" "來不尋常。" #: ../../library/argparse.rst:1176 msgid "" "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." msgstr "" "若要保持 *choices* 對使用者友善,請考慮使用自訂型別包裝器來轉換和格式化值,或" "是省略 type_ 並在你的應用程式碼中處理轉換。" #: ../../library/argparse.rst:1180 msgid "" "Formatted choices override the default *metavar* which is normally derived " "from *dest*. This is usually what you want because the user never sees the " "*dest* parameter. If this display isn't desirable (perhaps because there " "are many choices), just specify an explicit metavar_." msgstr "" "格式化的選擇會覆寫通常從 *dest* 衍生的預設 *metavar*。這通常是你想要的,因為" "使用者永遠看不到 *dest* 參數。如果此顯示不理想(也許因為有很多選擇),只需指" "定一個明確的 metavar_。" #: ../../library/argparse.rst:1189 msgid "required" msgstr "required" #: ../../library/argparse.rst:1191 msgid "" "In general, the :mod:`!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 :meth:`~ArgumentParser.add_argument`::" msgstr "" "一般而言,:mod:`!argparse` 模組假定像 ``-f`` 和 ``--bar`` 這樣的旗標表示\\ *" "可選*\\ 引數,它們總是可以在命令列上被省略。若要使一個選項成為\\ *必要的*,可" "以為 :meth:`~ArgumentParser.add_argument` 的 ``required=`` 關鍵字引數指定 " "``True``: ::" #: ../../library/argparse.rst:1196 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', required=True)\n" ">>> parser.parse_args(['--foo', 'BAR'])\n" "Namespace(foo='BAR')\n" ">>> parser.parse_args([])\n" "usage: [-h] --foo FOO\n" ": error: the following arguments are required: --foo" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', required=True)\n" ">>> parser.parse_args(['--foo', 'BAR'])\n" "Namespace(foo='BAR')\n" ">>> parser.parse_args([])\n" "usage: [-h] --foo FOO\n" ": error: the following arguments are required: --foo" #: ../../library/argparse.rst:1204 msgid "" "As the example shows, if an option is marked as ``required``, :meth:" "`~ArgumentParser.parse_args` will report an error if that option is not " "present at the command line." msgstr "" "如範例所示,如果一個選項被標記為 ``required``,:meth:`~ArgumentParser." "parse_args` 會在該選項不在命令列上時報告錯誤。" #: ../../library/argparse.rst:1210 msgid "" "Required options are generally considered bad form because users expect " "*options* to be *optional*, and thus they should be avoided when possible." msgstr "" "必要選項一般認為是不良做法,因為使用者期望\\ *選項*\\ 是\\ *可選的*,因此應盡" "可能避免使用。" #: ../../library/argparse.rst:1217 msgid "help" msgstr "help" #: ../../library/argparse.rst:1219 msgid "" "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." msgstr "" "``help`` 值是一個包含引數簡短描述的字串。當使用者請求說明(通常是在命令列上使" "用 ``-h`` 或 ``--help``)時,這些 ``help`` 描述會與每個引數一起顯示。" #: ../../library/argparse.rst:1224 msgid "" "The ``help`` strings can include various format specifiers to avoid " "repetition of things like the program name or the argument default_. The " "available specifiers include the program name, ``%(prog)s`` and most keyword " "arguments to :meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, " "``%(type)s``, etc.::" msgstr "" "``help`` 字串可以包含各種格式說明符號以避免重複程式名稱或引數 default_ 之類的" "內容。可用的說明符號包括程式名稱 ``%(prog)s`` 以及 :meth:`~ArgumentParser." "add_argument` 的大多數關鍵字引數,例如 ``%(default)s``、``%(type)s`` 等: ::" #: ../../library/argparse.rst:1229 msgid "" ">>> parser = argparse.ArgumentParser(prog='frobble')\n" ">>> parser.add_argument('bar', nargs='?', type=int, default=42,\n" "... help='the bar to %(prog)s (default: %(default)s)')\n" ">>> parser.print_help()\n" "usage: frobble [-h] [bar]\n" "\n" "positional arguments:\n" " bar the bar to frobble (default: 42)\n" "\n" "options:\n" " -h, --help show this help message and exit" msgstr "" ">>> parser = argparse.ArgumentParser(prog='frobble')\n" ">>> parser.add_argument('bar', nargs='?', type=int, default=42,\n" "... help='the bar to %(prog)s (default: %(default)s)')\n" ">>> parser.print_help()\n" "usage: frobble [-h] [bar]\n" "\n" "positional arguments:\n" " bar the bar to frobble (default: 42)\n" "\n" "options:\n" " -h, --help show this help message and exit" #: ../../library/argparse.rst:1241 msgid "" "As the help string supports %-formatting, if you want a literal ``%`` to " "appear in the help string, you must escape it as ``%%``." msgstr "" "由於 help 字串支援 %-格式化,如果你想讓文字 ``%`` 出現在 help 字串中,你必須" "將它跳脫為 ``%%``。" #: ../../library/argparse.rst:1244 msgid "" ":mod:`!argparse` supports silencing the help entry for certain options, by " "setting the ``help`` value to ``argparse.SUPPRESS``::" msgstr "" ":mod:`!argparse` 支援透過將 ``help`` 值設為 ``argparse.SUPPRESS`` 來隱藏某些" "選項的說明條目: ::" #: ../../library/argparse.rst:1247 msgid "" ">>> parser = argparse.ArgumentParser(prog='frobble')\n" ">>> parser.add_argument('--foo', help=argparse.SUPPRESS)\n" ">>> parser.print_help()\n" "usage: frobble [-h]\n" "\n" "options:\n" " -h, --help show this help message and exit" msgstr "" ">>> parser = argparse.ArgumentParser(prog='frobble')\n" ">>> parser.add_argument('--foo', help=argparse.SUPPRESS)\n" ">>> parser.print_help()\n" "usage: frobble [-h]\n" "\n" "options:\n" " -h, --help show this help message and exit" #: ../../library/argparse.rst:1259 msgid "metavar" msgstr "metavar" #: ../../library/argparse.rst:1261 msgid "" "When :class:`ArgumentParser` generates help messages, it needs some way to " "refer to each expected argument. By default, :class:`!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::" msgstr "" "當 :class:`ArgumentParser` 產生說明訊息時,它需要某種方式來指稱每個預期的引" "數。預設情況下,:class:`!ArgumentParser` 物件使用 dest_ 值作為每個物件的「名" "稱」。對於位置引數動作,預設直接使用 dest_ 值;對於可選引數動作,則將 dest_ " "值轉為大寫。因此,一個 ``dest='bar'`` 的位置引數稱為 ``bar``。一個應後接單一" "命令列引數的 ``--foo`` 可選引數稱為 ``FOO``。範例: ::" #: ../../library/argparse.rst:1270 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_args('X --foo Y'.split())\n" "Namespace(bar='X', foo='Y')\n" ">>> parser.print_help()\n" "usage: [-h] [--foo FOO] bar\n" "\n" "positional arguments:\n" " bar\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo FOO" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_args('X --foo Y'.split())\n" "Namespace(bar='X', foo='Y')\n" ">>> parser.print_help()\n" "usage: [-h] [--foo FOO] bar\n" "\n" "positional arguments:\n" " bar\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo FOO" #: ../../library/argparse.rst:1285 msgid "An alternative name can be specified with ``metavar``::" msgstr "可以用 ``metavar`` 指定替代名稱: ::" #: ../../library/argparse.rst:1287 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', metavar='YYY')\n" ">>> parser.add_argument('bar', metavar='XXX')\n" ">>> parser.parse_args('X --foo Y'.split())\n" "Namespace(bar='X', foo='Y')\n" ">>> parser.print_help()\n" "usage: [-h] [--foo YYY] XXX\n" "\n" "positional arguments:\n" " XXX\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo YYY" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', metavar='YYY')\n" ">>> parser.add_argument('bar', metavar='XXX')\n" ">>> parser.parse_args('X --foo Y'.split())\n" "Namespace(bar='X', foo='Y')\n" ">>> parser.print_help()\n" "usage: [-h] [--foo YYY] XXX\n" "\n" "positional arguments:\n" " XXX\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo YYY" #: ../../library/argparse.rst:1302 msgid "" "Note that ``metavar`` only changes the *displayed* name - the name of the " "attribute on the :meth:`~ArgumentParser.parse_args` object is still " "determined by the dest_ value." msgstr "" "請注意 ``metavar`` 只會更改\\ *顯示*\\ 的名稱——:meth:`~ArgumentParser." "parse_args` 物件上的屬性名稱仍由 dest_ 值決定。" #: ../../library/argparse.rst:1306 msgid "" "Different values of ``nargs`` may cause the metavar to be used multiple " "times. Providing a tuple to ``metavar`` specifies a different display for " "each of the arguments::" msgstr "" "不同的 ``nargs`` 值可能導致 metavar 被多次使用。提供一個元組給 ``metavar`` 可" "以為每個引數指定不同的顯示: ::" #: ../../library/argparse.rst:1310 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x', nargs=2)\n" ">>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))\n" ">>> parser.print_help()\n" "usage: PROG [-h] [-x X X] [--foo bar baz]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " -x X X\n" " --foo bar baz" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x', nargs=2)\n" ">>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))\n" ">>> parser.print_help()\n" "usage: PROG [-h] [-x X X] [--foo bar baz]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " -x X X\n" " --foo bar baz" #: ../../library/argparse.rst:1325 msgid "dest" msgstr "dest" #: ../../library/argparse.rst:1327 msgid "" "Most :class:`ArgumentParser` actions add some value as an attribute of the " "object returned by :meth:`~ArgumentParser.parse_args`. The name of this " "attribute is determined by the ``dest`` keyword argument of :meth:" "`~ArgumentParser.add_argument`. For positional argument actions, ``dest`` " "is normally supplied as the first argument to :meth:`~ArgumentParser." "add_argument`::" msgstr "" "大多數 :class:`ArgumentParser` action 會將某個值作為 :meth:`~ArgumentParser." "parse_args` 回傳物件的屬性加入。此屬性的名稱由 :meth:`~ArgumentParser." "add_argument` 的 ``dest`` 關鍵字引數決定。對於位置引數 action,``dest`` 通常" "作為 :meth:`~ArgumentParser.add_argument` 的第一個引數提供: ::" #: ../../library/argparse.rst:1334 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_args(['XXX'])\n" "Namespace(bar='XXX')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_args(['XXX'])\n" "Namespace(bar='XXX')" #: ../../library/argparse.rst:1339 msgid "" "For optional argument actions, the value of ``dest`` is normally inferred " "from the option strings. :class:`ArgumentParser` generates the value of " "``dest`` by taking the first long option string and stripping away the " "initial ``--`` string. If no long option strings were supplied, ``dest`` " "will be derived from the first short option string by stripping the initial " "``-`` character. Any internal ``-`` characters will be converted to ``_`` " "characters to make sure the string is a valid attribute name. The examples " "below illustrate this behavior::" msgstr "" "對於可選引數 action,``dest`` 的值通常從選項字串推斷。:class:" "`ArgumentParser` 透過取第一個長選項字串並去除開頭的 ``--`` 字串來產生 " "``dest`` 的值。如果沒有提供長選項字串,``dest`` 會從第一個短選項字串去除開頭" "的 ``-`` 字元來衍生。任何內部的 ``-`` 字元都會轉為 ``_`` 字元,以確保該字串是" "有效的屬性名稱。以下範例說明了此行為: ::" #: ../../library/argparse.rst:1348 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('-f', '--foo-bar', '--foo')\n" ">>> parser.add_argument('-x', '-y')\n" ">>> parser.parse_args('-f 1 -x 2'.split())\n" "Namespace(foo_bar='1', x='2')\n" ">>> parser.parse_args('--foo 1 -y 2'.split())\n" "Namespace(foo_bar='1', x='2')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('-f', '--foo-bar', '--foo')\n" ">>> parser.add_argument('-x', '-y')\n" ">>> parser.parse_args('-f 1 -x 2'.split())\n" "Namespace(foo_bar='1', x='2')\n" ">>> parser.parse_args('--foo 1 -y 2'.split())\n" "Namespace(foo_bar='1', x='2')" #: ../../library/argparse.rst:1356 msgid "``dest`` allows a custom attribute name to be provided::" msgstr "``dest`` 允許提供自訂的屬性名稱: ::" #: ../../library/argparse.rst:1358 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', dest='bar')\n" ">>> parser.parse_args('--foo XXX'.split())\n" "Namespace(bar='XXX')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', dest='bar')\n" ">>> parser.parse_args('--foo XXX'.split())\n" "Namespace(bar='XXX')" #: ../../library/argparse.rst:1367 msgid "deprecated" msgstr "deprecated" #: ../../library/argparse.rst:1369 msgid "" "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 :meth:`~ArgumentParser.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 :data:`sys.stderr` when the argument is used::" msgstr "" "在專案的生命週期中,某些引數可能需要從命令列移除。在移除它們之前,你應告知使" "用者這些引數已棄用且即將移除。:meth:`~ArgumentParser.add_argument` 的 " "``deprecated`` 關鍵字引數(預設為 ``False``)指定引數是否已棄用並將在未來移" "除。對於引數,如果 ``deprecated`` 為 ``True``,那麼使用該引數時會向 :data:" "`sys.stderr` 印出警告: ::" #: ../../library/argparse.rst:1379 msgid "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser(prog='snake.py')\n" ">>> parser.add_argument('--legs', default=0, type=int, deprecated=True)\n" ">>> parser.parse_args([])\n" "Namespace(legs=0)\n" ">>> parser.parse_args(['--legs', '4'])\n" "snake.py: warning: option '--legs' is deprecated\n" "Namespace(legs=4)" msgstr "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser(prog='snake.py')\n" ">>> parser.add_argument('--legs', default=0, type=int, deprecated=True)\n" ">>> parser.parse_args([])\n" "Namespace(legs=0)\n" ">>> parser.parse_args(['--legs', '4'])\n" "snake.py: warning: option '--legs' is deprecated\n" "Namespace(legs=4)" #: ../../library/argparse.rst:1392 msgid "Action classes" msgstr "Action 類別" #: ../../library/argparse.rst:1394 msgid "" ":class:`!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 :meth:" "`~ArgumentParser.add_argument`." msgstr "" ":class:`!Action` 類別實作了 Action API,為一個可呼叫物件,會回傳能夠處理來自" "命令列引數的可呼叫物件。任何遵循此 API 的物件都可以作為 ``action`` 參數傳給 :" "meth:`~ArgumentParser.add_argument`。" #: ../../library/argparse.rst:1403 msgid "" ":class:`!Action` objects are used by an :class:`ArgumentParser` to represent " "the information needed to parse a single argument from one or more strings " "from the command line. The :class:`!Action` class must accept the two " "positional arguments plus any keyword arguments passed to :meth:" "`ArgumentParser.add_argument` except for the ``action`` itself." msgstr "" ":class:`!Action` 物件被 :class:`ArgumentParser` 用來表示從命令列的一個或多個" "字串中剖析單個引數所需的資訊。:class:`!Action` 類別必須接受兩個位置引數以及傳" "給 :meth:`ArgumentParser.add_argument` 的任何關鍵字引數(除了 ``action`` 本" "身)。" #: ../../library/argparse.rst:1409 msgid "" "Instances of :class:`!Action` (or return value of any callable to the " "``action`` parameter) should have attributes :attr:`!dest`, :attr:`!" "option_strings`, :attr:`!default`, :attr:`!type`, :attr:`!required`, :attr:`!" "help`, etc. defined. The easiest way to ensure these attributes are defined " "is to call :meth:`!Action.__init__`." msgstr "" ":class:`!Action` 的實例(或任何傳給 ``action`` 參數的可呼叫物件的回傳值)應定" "義 :attr:`!dest`、:attr:`!option_strings`、:attr:`!default`、:attr:`!type`、:" "attr:`!required`、:attr:`!help` 等屬性。確保這些屬性被定義的最簡單方式是呼" "叫 :meth:`!Action.__init__`。" #: ../../library/argparse.rst:1417 msgid "" ":class:`!Action` instances should be callable, so subclasses must override " "the :meth:`!__call__` method, which should accept four parameters:" msgstr "" ":class:`!Action` 實例應該是可呼叫的,因此子類別必須覆寫 :meth:`!__call__` 方" "法,它應接受四個參數:" #: ../../library/argparse.rst:1420 msgid "" "*parser* - The :class:`ArgumentParser` object which contains this action." msgstr "*parser* - 包含此 action 的 :class:`ArgumentParser` 物件。" #: ../../library/argparse.rst:1422 msgid "" "*namespace* - The :class:`Namespace` object that will be returned by :meth:" "`~ArgumentParser.parse_args`. Most actions add an attribute to this object " "using :func:`setattr`." msgstr "" "*namespace* - 將由 :meth:`~ArgumentParser.parse_args` 回傳的 :class:" "`Namespace` 物件。大多數 action 使用 :func:`setattr` 將屬性加入此物件。" #: ../../library/argparse.rst:1426 msgid "" "*values* - The associated command-line arguments, with any type conversions " "applied. Type conversions are specified with the type_ keyword argument to :" "meth:`~ArgumentParser.add_argument`." msgstr "" "*values* - 相關聯的命令列引數,已套用任何型別轉換。型別轉換透過 :meth:" "`~ArgumentParser.add_argument` 的 type_ 關鍵字引數指定。" #: ../../library/argparse.rst:1430 msgid "" "*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." msgstr "" "*option_string* - 用來呼叫此 action 的選項字串。``option_string`` 引數是可選" "的,如果 action 與位置引數關聯則不會出現。" #: ../../library/argparse.rst:1434 msgid "" "The :meth:`!__call__` method may perform arbitrary actions, but will " "typically set attributes on the ``namespace`` based on ``dest`` and " "``values``." msgstr "" ":meth:`!__call__` 方法可以執行任意動作,但通常會根據 ``dest`` 和 ``values`` " "在 ``namespace`` 上設定屬性。" #: ../../library/argparse.rst:1439 msgid "" ":class:`!Action` subclasses can define a :meth:`!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." msgstr "" ":class:`!Action` 子類別可以定義一個 :meth:`!format_usage` 方法,它不接受引數" "並回傳一個字串,該字串會在印出程式用法時使用。如果未提供此方法,會使用合理的" "預設值。" #: ../../library/argparse.rst:1445 msgid "" "A subclass of :class:`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::" msgstr "" ":class:`Action` 的子類別,用於處理具有正向和負向選項的布林旗標。加入像 ``--" "foo`` 這樣的單個引數會自動建立 ``--foo`` 和 ``--no-foo`` 選項,其分別儲存 " "``True`` 和 ``False``: ::" #: ../../library/argparse.rst:1450 msgid "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)\n" ">>> parser.parse_args(['--no-foo'])\n" "Namespace(foo=False)" msgstr "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)\n" ">>> parser.parse_args(['--no-foo'])\n" "Namespace(foo=False)" #: ../../library/argparse.rst:1460 msgid "The parse_args() method" msgstr "parse_args() 方法" #: ../../library/argparse.rst:1464 msgid "" "Convert argument strings to objects and assign them as attributes of the " "namespace. Return the populated namespace." msgstr "" "將引數字串轉換為物件並將它們指定為命名空間的屬性。回傳填充後的命名空間。" #: ../../library/argparse.rst:1467 msgid "" "Previous calls to :meth:`add_argument` determine exactly what objects are " "created and how they are assigned. See the documentation for :meth:`!" "add_argument` for details." msgstr "" "先前對 :meth:`add_argument` 的呼叫決定了確切建立什麼物件以及如何指定它們。詳" "情請參閱 :meth:`!add_argument` 的文件。" #: ../../library/argparse.rst:1471 msgid "" "args_ - List of strings to parse. The default is taken from :data:`sys." "argv`." msgstr "args_ - 要剖析的字串串列。預設值取自 :data:`sys.argv`。" #: ../../library/argparse.rst:1474 msgid "" "namespace_ - An object to take the attributes. The default is a new empty :" "class:`Namespace` object." msgstr "" "namespace_ - 接收屬性的物件。預設值是一個新的空 :class:`Namespace` 物件。" #: ../../library/argparse.rst:1479 msgid "Option value syntax" msgstr "選項值語法" #: ../../library/argparse.rst:1481 msgid "" "The :meth:`~ArgumentParser.parse_args` method supports several ways of " "specifying the value of an option (if it takes one). In the simplest case, " "the option and its value are passed as two separate arguments::" msgstr "" ":meth:`~ArgumentParser.parse_args` 方法支援多種方式來指定選項的值(如果它接受" "值的話)。在最簡單的情況下,選項和它的值作為兩個獨立的引數傳入: ::" #: ../../library/argparse.rst:1485 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x')\n" ">>> parser.add_argument('--foo')\n" ">>> parser.parse_args(['-x', 'X'])\n" "Namespace(foo=None, x='X')\n" ">>> parser.parse_args(['--foo', 'FOO'])\n" "Namespace(foo='FOO', x=None)" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x')\n" ">>> parser.add_argument('--foo')\n" ">>> parser.parse_args(['-x', 'X'])\n" "Namespace(foo=None, x='X')\n" ">>> parser.parse_args(['--foo', 'FOO'])\n" "Namespace(foo='FOO', x=None)" #: ../../library/argparse.rst:1493 msgid "" "For long options (options with names longer than a single character), the " "option and value can also be passed as a single command-line argument, using " "``=`` to separate them::" msgstr "" "對於長選項(名稱長度超過一個字元的選項),選項和值也可以作為單個命令列引數傳" "入,使用 ``=`` 來分隔它們: ::" #: ../../library/argparse.rst:1497 msgid "" ">>> parser.parse_args(['--foo=FOO'])\n" "Namespace(foo='FOO', x=None)" msgstr "" ">>> parser.parse_args(['--foo=FOO'])\n" "Namespace(foo='FOO', x=None)" #: ../../library/argparse.rst:1500 msgid "" "For short options (options only one character long), the option and its " "value can be concatenated::" msgstr "對於短選項(只有一個字元長的選項),選項和它的值可以串接在一起: ::" #: ../../library/argparse.rst:1503 msgid "" ">>> parser.parse_args(['-xX'])\n" "Namespace(foo=None, x='X')" msgstr "" ">>> parser.parse_args(['-xX'])\n" "Namespace(foo=None, x='X')" #: ../../library/argparse.rst:1506 msgid "" "Several short options can be joined together, using only a single ``-`` " "prefix, as long as only the last option (or none of them) requires a value::" msgstr "" "如果只有最後一個選項需要值(或都不需要),多個短選項就可以被合併在一起、只使" "用一個 ``-`` 前綴: ::" #: ../../library/argparse.rst:1509 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x', action='store_true')\n" ">>> parser.add_argument('-y', action='store_true')\n" ">>> parser.add_argument('-z')\n" ">>> parser.parse_args(['-xyzZ'])\n" "Namespace(x=True, y=True, z='Z')" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x', action='store_true')\n" ">>> parser.add_argument('-y', action='store_true')\n" ">>> parser.add_argument('-z')\n" ">>> parser.parse_args(['-xyzZ'])\n" "Namespace(x=True, y=True, z='Z')" #: ../../library/argparse.rst:1518 msgid "Invalid arguments" msgstr "無效引數" #: ../../library/argparse.rst:1520 msgid "" "While parsing the command line, :meth:`~ArgumentParser.parse_args` checks " "for a variety of errors, including ambiguous options, invalid types, invalid " "options, wrong number of positional arguments, etc. When it encounters such " "an error, it exits and prints the error along with a usage message::" msgstr "" "在剖析命令列時,:meth:`~ArgumentParser.parse_args` 會檢查各種錯誤,包括有歧義" "的選項、無效的型別、無效的選項、錯誤的位置引數數量等。當遇到此類錯誤時,它會" "退出並印出錯誤及用法訊息: ::" #: ../../library/argparse.rst:1525 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--foo', type=int)\n" ">>> parser.add_argument('bar', nargs='?')\n" "\n" ">>> # invalid type\n" ">>> parser.parse_args(['--foo', 'spam'])\n" "usage: PROG [-h] [--foo FOO] [bar]\n" "PROG: error: argument --foo: invalid int value: 'spam'\n" "\n" ">>> # invalid option\n" ">>> parser.parse_args(['--bar'])\n" "usage: PROG [-h] [--foo FOO] [bar]\n" "PROG: error: no such option: --bar\n" "\n" ">>> # wrong number of arguments\n" ">>> parser.parse_args(['spam', 'badger'])\n" "usage: PROG [-h] [--foo FOO] [bar]\n" "PROG: error: extra arguments found: badger" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--foo', type=int)\n" ">>> parser.add_argument('bar', nargs='?')\n" "\n" ">>> # 無效型別\n" ">>> parser.parse_args(['--foo', 'spam'])\n" "usage: PROG [-h] [--foo FOO] [bar]\n" "PROG: error: argument --foo: invalid int value: 'spam'\n" "\n" ">>> # 無效選項\n" ">>> parser.parse_args(['--bar'])\n" "usage: PROG [-h] [--foo FOO] [bar]\n" "PROG: error: no such option: --bar\n" "\n" ">>> # 錯誤引數數量\n" ">>> parser.parse_args(['spam', 'badger'])\n" "usage: PROG [-h] [--foo FOO] [bar]\n" "PROG: error: extra arguments found: badger" #: ../../library/argparse.rst:1546 msgid "Arguments containing ``-``" msgstr "包含 ``-`` 的引數" #: ../../library/argparse.rst:1548 msgid "" "The :meth:`~ArgumentParser.parse_args` method attempts to give errors " "whenever the user has clearly made a mistake, but some situations are " "inherently ambiguous. For example, the command-line argument ``-1`` could " "either be an attempt to specify an option or an attempt to provide a " "positional argument. The :meth:`~ArgumentParser.parse_args` method is " "cautious here: positional arguments may only begin with ``-`` if they look " "like negative numbers and there are no options in the parser that look like " "negative numbers::" msgstr "" ":meth:`~ArgumentParser.parse_args` 方法嘗試在使用者明顯犯錯時給出錯誤,但有些" "情況本質上是有歧義的。例如命令列引數 ``-1`` 既可能是嘗試指定一個選項,也可能" "是嘗試提供一個位置引數。:meth:`~ArgumentParser.parse_args` 方法在此處很謹慎:" "位置引數只有在看起來像負數且剖析器中沒有看起來像負數的選項時,才可以用 ``-`` " "開頭: ::" #: ../../library/argparse.rst:1556 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x')\n" ">>> parser.add_argument('foo', nargs='?')\n" "\n" ">>> # no negative number options, so -1 is a positional argument\n" ">>> parser.parse_args(['-x', '-1'])\n" "Namespace(foo=None, x='-1')\n" "\n" ">>> # no negative number options, so -1 and -5 are positional arguments\n" ">>> parser.parse_args(['-x', '-1', '-5'])\n" "Namespace(foo='-5', x='-1')\n" "\n" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-1', dest='one')\n" ">>> parser.add_argument('foo', nargs='?')\n" "\n" ">>> # negative number options present, so -1 is an option\n" ">>> parser.parse_args(['-1', 'X'])\n" "Namespace(foo=None, one='X')\n" "\n" ">>> # negative number options present, so -2 is an option\n" ">>> parser.parse_args(['-2'])\n" "usage: PROG [-h] [-1 ONE] [foo]\n" "PROG: error: no such option: -2\n" "\n" ">>> # negative number options present, so both -1s are options\n" ">>> parser.parse_args(['-1', '-1'])\n" "usage: PROG [-h] [-1 ONE] [foo]\n" "PROG: error: argument -1: expected one argument" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-x')\n" ">>> parser.add_argument('foo', nargs='?')\n" "\n" ">>> # 沒有負數選項,所以 -1 是位置引數\n" ">>> parser.parse_args(['-x', '-1'])\n" "Namespace(foo=None, x='-1')\n" "\n" ">>> # 沒有負數選項,所以 -1 和 -5 是位置引數\n" ">>> parser.parse_args(['-x', '-1', '-5'])\n" "Namespace(foo='-5', x='-1')\n" "\n" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-1', dest='one')\n" ">>> parser.add_argument('foo', nargs='?')\n" "\n" ">>> # 有負數選項存在,所以 -1 是選項\n" ">>> parser.parse_args(['-1', 'X'])\n" "Namespace(foo=None, one='X')\n" "\n" ">>> # 有負數選項存在,所以 -2 是選項\n" ">>> parser.parse_args(['-2'])\n" "usage: PROG [-h] [-1 ONE] [foo]\n" "PROG: error: no such option: -2\n" "\n" ">>> # 有負數選項存在,所以兩個 -1 都是選項\n" ">>> parser.parse_args(['-1', '-1'])\n" "usage: PROG [-h] [-1 ONE] [foo]\n" "PROG: error: argument -1: expected one argument" #: ../../library/argparse.rst:1586 msgid "" "If you have positional arguments that must begin with ``-`` and don't look " "like negative numbers, you can insert the pseudo-argument ``'--'`` which " "tells :meth:`~ArgumentParser.parse_args` that everything after that is a " "positional argument::" msgstr "" "如果你有必須以 ``-`` 開頭且不像負數的位置引數,你可以插入偽引數 ``'--'``,它" "會告訴 :meth:`~ArgumentParser.parse_args` 在此之後的所有內容都是位置引數: ::" #: ../../library/argparse.rst:1591 msgid "" ">>> parser.parse_args(['--', '-f'])\n" "Namespace(foo='-f', one=None)" msgstr "" ">>> parser.parse_args(['--', '-f'])\n" "Namespace(foo='-f', one=None)" #: ../../library/argparse.rst:1594 msgid "" "See also :ref:`the argparse howto on ambiguous arguments ` for more details." msgstr "" "更多詳情請參閱 :ref:`argparse howto 中關於有歧義引數的說明 `。" #: ../../library/argparse.rst:1600 msgid "Argument abbreviations (prefix matching)" msgstr "引數縮寫 (前綴匹配)" #: ../../library/argparse.rst:1602 msgid "" "The :meth:`~ArgumentParser.parse_args` method :ref:`by default " "` allows long options to be abbreviated to a prefix, if the " "abbreviation is unambiguous (the prefix matches a unique option)::" msgstr "" ":meth:`~ArgumentParser.parse_args` 方法\\ :ref:`預設 `\\ 允許長" "選項被縮寫為前綴,只要縮寫是無歧義的(前綴匹配到唯一的選項): ::" #: ../../library/argparse.rst:1606 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-bacon')\n" ">>> parser.add_argument('-badger')\n" ">>> parser.parse_args('-bac MMM'.split())\n" "Namespace(bacon='MMM', badger=None)\n" ">>> parser.parse_args('-bad WOOD'.split())\n" "Namespace(bacon=None, badger='WOOD')\n" ">>> parser.parse_args('-ba BA'.split())\n" "usage: PROG [-h] [-bacon BACON] [-badger BADGER]\n" "PROG: error: ambiguous option: -ba could match -badger, -bacon" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('-bacon')\n" ">>> parser.add_argument('-badger')\n" ">>> parser.parse_args('-bac MMM'.split())\n" "Namespace(bacon='MMM', badger=None)\n" ">>> parser.parse_args('-bad WOOD'.split())\n" "Namespace(bacon=None, badger='WOOD')\n" ">>> parser.parse_args('-ba BA'.split())\n" "usage: PROG [-h] [-bacon BACON] [-badger BADGER]\n" "PROG: error: ambiguous option: -ba could match -badger, -bacon" #: ../../library/argparse.rst:1617 msgid "" "An error is produced for arguments that could produce more than one options. " "This feature can be disabled by setting :ref:`allow_abbrev` to ``False``." msgstr "" "對於可能產生多個選項的引數會產生錯誤。可以透過將 :ref:`allow_abbrev` 設為 " "``False`` 來停用此功能。" #: ../../library/argparse.rst:1623 msgid "Beyond ``sys.argv``" msgstr "``sys.argv`` 之外" #: ../../library/argparse.rst:1625 msgid "" "Sometimes it may be useful to have an :class:`ArgumentParser` parse " "arguments other than those of :data:`sys.argv`. This can be accomplished by " "passing a list of strings to :meth:`~ArgumentParser.parse_args`. This is " "useful for testing at the interactive prompt::" msgstr "" "有時候讓 :class:`ArgumentParser` 剖析 :data:`sys.argv` 以外的引數可能很有用。" "這可以透過將字串串列傳給 :meth:`~ArgumentParser.parse_args` 來完成。這對於在" "互動式提示中測試很有用: ::" #: ../../library/argparse.rst:1630 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument(\n" "... 'integers', metavar='int', type=int, choices=range(10),\n" "... nargs='+', help='an integer in the range 0..9')\n" ">>> parser.add_argument(\n" "... '--sum', dest='accumulate', action='store_const', const=sum,\n" "... default=max, help='sum the integers (default: find the max)')\n" ">>> parser.parse_args(['1', '2', '3', '4'])\n" "Namespace(accumulate=, integers=[1, 2, 3, 4])\n" ">>> parser.parse_args(['1', '2', '3', '4', '--sum'])\n" "Namespace(accumulate=, integers=[1, 2, 3, 4])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument(\n" "... 'integers', metavar='int', type=int, choices=range(10),\n" "... nargs='+', help='an integer in the range 0..9')\n" ">>> parser.add_argument(\n" "... '--sum', dest='accumulate', action='store_const', const=sum,\n" "... default=max, help='sum the integers (default: find the max)')\n" ">>> parser.parse_args(['1', '2', '3', '4'])\n" "Namespace(accumulate=, integers=[1, 2, 3, 4])\n" ">>> parser.parse_args(['1', '2', '3', '4', '--sum'])\n" "Namespace(accumulate=, integers=[1, 2, 3, 4])" #: ../../library/argparse.rst:1645 msgid "The Namespace object" msgstr "命名空間物件" #: ../../library/argparse.rst:1649 msgid "" "Simple class used by default by :meth:`~ArgumentParser.parse_args` to create " "an object holding attributes and return it." msgstr "" ":meth:`~ArgumentParser.parse_args` 預設使用的簡單類別,用來建立保存屬性的物件" "並回傳它。" #: ../../library/argparse.rst:1652 msgid "" "This class is deliberately simple, just an :class:`object` subclass with a " "readable string representation. If you prefer to have dict-like view of the " "attributes, you can use the standard Python idiom, :func:`vars`::" msgstr "" "這個類別刻意保持簡單,只是一個具有可讀字串表示的 :class:`object` 子類別。如果" "你偏好以類字典的方式檢視屬性,可以使用標準 Python 慣用寫法 :func:`vars`: ::" #: ../../library/argparse.rst:1656 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> args = parser.parse_args(['--foo', 'BAR'])\n" ">>> vars(args)\n" "{'foo': 'BAR'}" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> args = parser.parse_args(['--foo', 'BAR'])\n" ">>> vars(args)\n" "{'foo': 'BAR'}" #: ../../library/argparse.rst:1662 msgid "" "It may also be useful to have an :class:`ArgumentParser` assign attributes " "to an already existing object, rather than a new :class:`Namespace` object. " "This can be achieved by specifying the ``namespace=`` keyword argument::" msgstr "" "讓 :class:`ArgumentParser` 將屬性指定給已存在的物件而非新的 :class:" "`Namespace` 物件也可能很有用。這可以透過指定 ``namespace=`` 關鍵字引數來達" "成: ::" #: ../../library/argparse.rst:1666 msgid "" ">>> class C:\n" "... pass\n" "...\n" ">>> c = C()\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)\n" ">>> c.foo\n" "'BAR'" msgstr "" ">>> class C:\n" "... pass\n" "...\n" ">>> c = C()\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)\n" ">>> c.foo\n" "'BAR'" #: ../../library/argparse.rst:1678 msgid "Other utilities" msgstr "其他工具" #: ../../library/argparse.rst:1681 msgid "Subcommands" msgstr "子命令" #: ../../library/argparse.rst:1688 msgid "" "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. :class:" "`ArgumentParser` supports the creation of such subcommands with the :meth:`!" "add_subparsers` method. The :meth:`!add_subparsers` method is normally " "called with no arguments and returns a special action object. This object " "has a single method, :meth:`~_SubParsersAction.add_parser`, which takes a " "command name and any :class:`!ArgumentParser` constructor arguments, and " "returns an :class:`!ArgumentParser` object that can be modified as usual." msgstr "" "許多程式將其功能分割為數個子命令,例如 ``svn`` 程式可以呼叫 ``svn " "checkout``、``svn update`` 和 ``svn commit`` 等子命令。當程式執行多個需要不同" "種類命令列引數的不同功能時,以這種方式分割功能是特別好的做法。:class:" "`ArgumentParser` 透過 :meth:`!add_subparsers` 方法支援建立這類子命令。:meth:" "`!add_subparsers` 方法通常不帶引數呼叫,並回傳一個特殊的 action 物件。此物件" "有一個方法 :meth:`~_SubParsersAction.add_parser`,它接受命令名稱和任何 :" "class:`!ArgumentParser` 建構函式引數,並回傳一個可以像往常一樣修改的 :class:" "`!ArgumentParser` 物件。" #: ../../library/argparse.rst:1700 msgid "Description of parameters:" msgstr "參數的解釋:" #: ../../library/argparse.rst:1702 msgid "" "*title* - title for the sub-parser group in help output; by default " "\"subcommands\" if description is provided, otherwise uses title for " "positional arguments" msgstr "" "*title* - 說明輸出中子剖析器群組的標題;預設情況下,若有提供 description 則" "為 \"subcommands\",否則使用位置引數的標題" #: ../../library/argparse.rst:1706 msgid "" "*description* - description for the sub-parser group in help output, by " "default ``None``" msgstr "*description* - 說明輸出中子剖析器群組的描述,預設為 ``None``" #: ../../library/argparse.rst:1709 msgid "" "*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" msgstr "" "*prog* - 將與子命令說明一起顯示的用法資訊,預設為程式名稱和子剖析器引數之前的" "任何位置引數" #: ../../library/argparse.rst:1713 msgid "" "*parser_class* - class which will be used to create sub-parser instances, by " "default the class of the current parser (e.g. :class:`ArgumentParser`)" msgstr "" "*parser_class* - 將用來建立子剖析器實例的類別,預設為目前剖析器的類別(例如 :" "class:`ArgumentParser`)" #: ../../library/argparse.rst:1716 msgid "" "action_ - the basic type of action to be taken when this argument is " "encountered at the command line" msgstr "action_ - 在命令列遇到此引數時要執行的基本 action 類型" #: ../../library/argparse.rst:1719 msgid "" "dest_ - name of the attribute under which subcommand name will be stored; by " "default ``None`` and no value is stored" msgstr "dest_ - 用於儲存子命令名稱的屬性名稱;預設為 ``None`` 且不儲存任何值" #: ../../library/argparse.rst:1722 msgid "" "required_ - Whether or not a subcommand must be provided, by default " "``False`` (added in 3.7)" msgstr "required_ - 是否必須提供子命令,預設為 ``False``\\ (在 3.7 中新增)" #: ../../library/argparse.rst:1725 msgid "help_ - help for sub-parser group in help output, by default ``None``" msgstr "help_ - 說明輸出中子剖析器群組的說明,預設為 ``None``" #: ../../library/argparse.rst:1727 msgid "" "metavar_ - string presenting available subcommands in help; by default it is " "``None`` and presents subcommands in form {cmd1, cmd2, ..}" msgstr "" "metavar_ - 在說明中呈現可用子命令的字串;預設為 ``None`` 並以 {cmd1, " "cmd2, ..} 的形式呈現子命令" #: ../../library/argparse.rst:1730 msgid "Some example usage::" msgstr "一些使用範例: ::" #: ../../library/argparse.rst:1732 msgid "" ">>> # create the top-level parser\n" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--foo', action='store_true', help='foo help')\n" ">>> subparsers = parser.add_subparsers(help='subcommand help')\n" ">>>\n" ">>> # create the parser for the \"a\" command\n" ">>> parser_a = subparsers.add_parser('a', help='a help')\n" ">>> parser_a.add_argument('bar', type=int, help='bar help')\n" ">>>\n" ">>> # create the parser for the \"b\" command\n" ">>> parser_b = subparsers.add_parser('b', help='b help')\n" ">>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz " "help')\n" ">>>\n" ">>> # parse some argument lists\n" ">>> parser.parse_args(['a', '12'])\n" "Namespace(bar=12, foo=False)\n" ">>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])\n" "Namespace(baz='Z', foo=True)" msgstr "" ">>> # 建立頂層剖析器\n" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> parser.add_argument('--foo', action='store_true', help='foo help')\n" ">>> subparsers = parser.add_subparsers(help='subcommand help')\n" ">>>\n" ">>> # 建立 \"a\" 命令的剖析器\n" ">>> parser_a = subparsers.add_parser('a', help='a help')\n" ">>> parser_a.add_argument('bar', type=int, help='bar help')\n" ">>>\n" ">>> # 建立 \"b\" 命令的剖析器\n" ">>> parser_b = subparsers.add_parser('b', help='b help')\n" ">>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz " "help')\n" ">>>\n" ">>> # 剖析一些引數串列\n" ">>> parser.parse_args(['a', '12'])\n" "Namespace(bar=12, foo=False)\n" ">>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])\n" "Namespace(baz='Z', foo=True)" #: ../../library/argparse.rst:1751 msgid "" "Note that the object returned by :meth:`parse_args` will only contain " "attributes for the main parser and the subparser that was selected by the " "command line (and not any other subparsers). So in the example above, when " "the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are " "present, and when the ``b`` command is specified, only the ``foo`` and " "``baz`` attributes are present." msgstr "" "請注意 :meth:`parse_args` 回傳的物件只會包含主剖析器和命令列所選子剖析器的屬" "性(而非任何其他子剖析器)。因此在上面的範例中,當指定 ``a`` 命令時,只有 " "``foo`` 和 ``bar`` 屬性存在;當指定 ``b`` 命令時,只有 ``foo`` 和 ``baz`` 屬" "性存在。" #: ../../library/argparse.rst:1758 msgid "" "Similarly, when a help message is requested from a subparser, only the help " "for that particular parser will be printed. The help message will not " "include parent parser or sibling parser messages. (A help message for each " "subparser command, however, can be given by supplying the ``help=`` argument " "to :meth:`~_SubParsersAction.add_parser` as above.)" msgstr "" "同樣地,當從子剖析器請求說明訊息時,只會印出該特定剖析器的說明。說明訊息不會" "包含父剖析器或兄弟剖析器的訊息。(然而每個子剖析器命令的說明訊息可以透過如上" "所述向 :meth:`~_SubParsersAction.add_parser` 提供 ``help=`` 引數來給定。)" #: ../../library/argparse.rst:1766 msgid "" ">>> parser.parse_args(['--help'])\n" "usage: PROG [-h] [--foo] {a,b} ...\n" "\n" "positional arguments:\n" " {a,b} subcommand help\n" " a a help\n" " b b help\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo foo help\n" "\n" ">>> parser.parse_args(['a', '--help'])\n" "usage: PROG a [-h] bar\n" "\n" "positional arguments:\n" " bar bar help\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" ">>> parser.parse_args(['b', '--help'])\n" "usage: PROG b [-h] [--baz {X,Y,Z}]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --baz {X,Y,Z} baz help" msgstr "" ">>> parser.parse_args(['--help'])\n" "usage: PROG [-h] [--foo] {a,b} ...\n" "\n" "positional arguments:\n" " {a,b} subcommand help\n" " a a help\n" " b b help\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --foo foo help\n" "\n" ">>> parser.parse_args(['a', '--help'])\n" "usage: PROG a [-h] bar\n" "\n" "positional arguments:\n" " bar bar help\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" ">>> parser.parse_args(['b', '--help'])\n" "usage: PROG b [-h] [--baz {X,Y,Z}]\n" "\n" "options:\n" " -h, --help show this help message and exit\n" " --baz {X,Y,Z} baz help" #: ../../library/argparse.rst:1794 msgid "" "The :meth:`add_subparsers` method also supports ``title`` and " "``description`` keyword arguments. When either is present, the subparser's " "commands will appear in their own group in the help output. For example::" msgstr "" ":meth:`add_subparsers` 方法也支援 ``title`` 和 ``description`` 關鍵字引數。當" "任一者存在時,子剖析器的命令會在說明輸出中以自己的群組出現。例如: ::" #: ../../library/argparse.rst:1798 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers(title='subcommands',\n" "... description='valid subcommands',\n" "... help='additional help')\n" ">>> subparsers.add_parser('foo')\n" ">>> subparsers.add_parser('bar')\n" ">>> parser.parse_args(['-h'])\n" "usage: [-h] {foo,bar} ...\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "subcommands:\n" " valid subcommands\n" "\n" " {foo,bar} additional help" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers(title='subcommands',\n" "... description='valid subcommands',\n" "... help='additional help')\n" ">>> subparsers.add_parser('foo')\n" ">>> subparsers.add_parser('bar')\n" ">>> parser.parse_args(['-h'])\n" "usage: [-h] {foo,bar} ...\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "subcommands:\n" " valid subcommands\n" "\n" " {foo,bar} additional help" #: ../../library/argparse.rst:1815 msgid "" "Furthermore, :meth:`~_SubParsersAction.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``::" msgstr "" "此外,:meth:`~_SubParsersAction.add_parser` 支援一個額外的 *aliases* 引數,它" "允許多個字串參照同一個子剖析器。這個範例像 ``svn`` 一樣,將 ``co`` 作為 " "``checkout`` 的簡寫別名: ::" #: ../../library/argparse.rst:1820 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers()\n" ">>> checkout = subparsers.add_parser('checkout', aliases=['co'])\n" ">>> checkout.add_argument('foo')\n" ">>> parser.parse_args(['co', 'bar'])\n" "Namespace(foo='bar')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers()\n" ">>> checkout = subparsers.add_parser('checkout', aliases=['co'])\n" ">>> checkout.add_argument('foo')\n" ">>> parser.parse_args(['co', 'bar'])\n" "Namespace(foo='bar')" #: ../../library/argparse.rst:1827 msgid "" ":meth:`~_SubParsersAction.add_parser` supports also an additional " "*deprecated* argument, which allows to deprecate the subparser." msgstr "" ":meth:`~_SubParsersAction.add_parser` 也支援一個額外的 *deprecated* 引數,它" "允許棄用子剖析器。" #: ../../library/argparse.rst:1841 msgid "" "One particularly effective way of handling subcommands is to combine the use " "of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so " "that each subparser knows which Python function it should execute. For " "example::" msgstr "" "處理子命令的一個特別有效的方式是將 :meth:`add_subparsers` 方法的使用與 :meth:" "`set_defaults` 的呼叫結合,使每個子剖析器知道它應該執行哪個 Python 函式。例" "如: ::" #: ../../library/argparse.rst:1846 msgid "" ">>> # subcommand functions\n" ">>> def foo(args):\n" "... print(args.x * args.y)\n" "...\n" ">>> def bar(args):\n" "... print('((%s))' % args.z)\n" "...\n" ">>> # create the top-level parser\n" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers(required=True)\n" ">>>\n" ">>> # create the parser for the \"foo\" command\n" ">>> parser_foo = subparsers.add_parser('foo')\n" ">>> parser_foo.add_argument('-x', type=int, default=1)\n" ">>> parser_foo.add_argument('y', type=float)\n" ">>> parser_foo.set_defaults(func=foo)\n" ">>>\n" ">>> # create the parser for the \"bar\" command\n" ">>> parser_bar = subparsers.add_parser('bar')\n" ">>> parser_bar.add_argument('z')\n" ">>> parser_bar.set_defaults(func=bar)\n" ">>>\n" ">>> # parse the args and call whatever function was selected\n" ">>> args = parser.parse_args('foo 1 -x 2'.split())\n" ">>> args.func(args)\n" "2.0\n" ">>>\n" ">>> # parse the args and call whatever function was selected\n" ">>> args = parser.parse_args('bar XYZYX'.split())\n" ">>> args.func(args)\n" "((XYZYX))" msgstr "" ">>> # 子命令函式\n" ">>> def foo(args):\n" "... print(args.x * args.y)\n" "...\n" ">>> def bar(args):\n" "... print('((%s))' % args.z)\n" "...\n" ">>> # 建立頂層剖析器\n" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers(required=True)\n" ">>>\n" ">>> # 建立 \"foo\" 命令的剖析器\n" ">>> parser_foo = subparsers.add_parser('foo')\n" ">>> parser_foo.add_argument('-x', type=int, default=1)\n" ">>> parser_foo.add_argument('y', type=float)\n" ">>> parser_foo.set_defaults(func=foo)\n" ">>>\n" ">>> # 建立 \"bar\" 命令的剖析器\n" ">>> parser_bar = subparsers.add_parser('bar')\n" ">>> parser_bar.add_argument('z')\n" ">>> parser_bar.set_defaults(func=bar)\n" ">>>\n" ">>> # 剖析引數並呼叫所選的函式\n" ">>> args = parser.parse_args('foo 1 -x 2'.split())\n" ">>> args.func(args)\n" "2.0\n" ">>>\n" ">>> # 剖析引數並呼叫所選的函式\n" ">>> args = parser.parse_args('bar XYZYX'.split())\n" ">>> args.func(args)\n" "((XYZYX))" #: ../../library/argparse.rst:1878 msgid "" "This way, you can let :meth:`parse_args` do the job of calling the " "appropriate function after argument parsing is complete. Associating " "functions with actions like this is typically the easiest way to handle the " "different actions for each of your subparsers. However, if it is necessary " "to check the name of the subparser that was invoked, the ``dest`` keyword " "argument to the :meth:`add_subparsers` call will work::" msgstr "" "這樣你可以讓 :meth:`parse_args` 在引數剖析完成後負責呼叫適當的函式。像這樣將" "函式與 action 關聯通常是處理每個子剖析器不同動作的最簡單方式。然而如果有必要" "檢查被呼叫的子剖析器名稱,:meth:`add_subparsers` 呼叫的 ``dest`` 關鍵字引數可" "以達成此目的: ::" #: ../../library/argparse.rst:1885 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers(dest='subparser_name')\n" ">>> subparser1 = subparsers.add_parser('1')\n" ">>> subparser1.add_argument('-x')\n" ">>> subparser2 = subparsers.add_parser('2')\n" ">>> subparser2.add_argument('y')\n" ">>> parser.parse_args(['2', 'frobble'])\n" "Namespace(subparser_name='2', y='frobble')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> subparsers = parser.add_subparsers(dest='subparser_name')\n" ">>> subparser1 = subparsers.add_parser('1')\n" ">>> subparser1.add_argument('-x')\n" ">>> subparser2 = subparsers.add_parser('2')\n" ">>> subparser2.add_argument('y')\n" ">>> parser.parse_args(['2', 'frobble'])\n" "Namespace(subparser_name='2', y='frobble')" #: ../../library/argparse.rst:1894 msgid "New *required* keyword-only parameter." msgstr "新增 *required* 僅限關鍵字參數。" #: ../../library/argparse.rst:1897 msgid "" "Subparser's *prog* is no longer affected by a custom usage message in the " "main parser." msgstr "子剖析器的 *prog* 不再受主剖析器中自訂用法訊息的影響。" #: ../../library/argparse.rst:1903 msgid "FileType objects" msgstr "FileType 物件" #: ../../library/argparse.rst:1907 msgid "" "The :class:`FileType` factory creates objects that can be passed to the type " "argument of :meth:`ArgumentParser.add_argument`. Arguments that have :class:" "`FileType` objects as their type will open command-line arguments as files " "with the requested modes, buffer sizes, encodings and error handling (see " "the :func:`open` function for more details)::" msgstr "" ":class:`FileType` 工廠建立可以傳給 :meth:`ArgumentParser.add_argument` 的 " "type 引數的物件。以 :class:`FileType` 物件作為其型別的引數會以請求的模式、緩" "衝區大小、編碼和錯誤處理開啟命令列引數作為檔案(更多詳情請參閱 :func:`open` " "函式): ::" #: ../../library/argparse.rst:1913 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))\n" ">>> parser.add_argument('out', type=argparse.FileType('w', " "encoding='UTF-8'))\n" ">>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])\n" "Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, " "raw=<_io.FileIO name='raw.dat' mode='wb'>)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))\n" ">>> parser.add_argument('out', type=argparse.FileType('w', " "encoding='UTF-8'))\n" ">>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])\n" "Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, " "raw=<_io.FileIO name='raw.dat' mode='wb'>)" #: ../../library/argparse.rst:1919 msgid "" "FileType objects understand the pseudo-argument ``'-'`` and automatically " "convert this into :data:`sys.stdin` for readable :class:`FileType` objects " "and :data:`sys.stdout` for writable :class:`FileType` objects::" msgstr "" "FileType 物件能理解偽引數 ``'-'``,並自動將其轉換為可讀 :class:`FileType` 物" "件的 :data:`sys.stdin` 和可寫 :class:`FileType` 物件的 :data:`sys." "stdout`: ::" #: ../../library/argparse.rst:1923 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('infile', type=argparse.FileType('r'))\n" ">>> parser.parse_args(['-'])\n" "Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('infile', type=argparse.FileType('r'))\n" ">>> parser.parse_args(['-'])\n" "Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" #: ../../library/argparse.rst:1930 msgid "" "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 :keyword:`with`-statement to " "manage the files." msgstr "" "如果一個引數使用了 *FileType* 然後後續的引數失敗了,雖然會報告錯誤但檔案不會" "自動關閉。這也可能覆蓋輸出檔案。在這種情況下,最好等到剖析器執行完畢後,再使" "用 :keyword:`with` 陳述式來管理檔案。" #: ../../library/argparse.rst:1936 msgid "Added the *encoding* and *errors* parameters." msgstr "新增了 *encoding* 和 *errors* 參數。" #: ../../library/argparse.rst:1943 msgid "Argument groups" msgstr "引數群組" #: ../../library/argparse.rst:1948 msgid "" "By default, :class:`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 :meth:`!add_argument_group` " "method::" msgstr "" "預設情況下,:class:`ArgumentParser` 在顯示說明訊息時會將命令列引數分成「位置" "引數」和「選項」兩組。當引數有比此預設分組更好的概念性分組時,可以使用 :meth:" "`!add_argument_group` 方法建立適當的群組: ::" #: ../../library/argparse.rst:1954 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" ">>> group = parser.add_argument_group('group')\n" ">>> group.add_argument('--foo', help='foo help')\n" ">>> group.add_argument('bar', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [--foo FOO] bar\n" "\n" "group:\n" " bar bar help\n" " --foo FOO foo help" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" ">>> group = parser.add_argument_group('group')\n" ">>> group.add_argument('--foo', help='foo help')\n" ">>> group.add_argument('bar', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [--foo FOO] bar\n" "\n" "group:\n" " bar bar help\n" " --foo FOO foo help" #: ../../library/argparse.rst:1965 msgid "" "The :meth:`add_argument_group` method returns an argument group object which " "has an :meth:`~ArgumentParser.add_argument` method just like a regular :" "class:`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 :meth:`!add_argument_group` method " "accepts *title* and *description* arguments which can be used to customize " "this display::" msgstr "" ":meth:`add_argument_group` 方法回傳一個引數群組物件,它具有與一般 :class:" "`ArgumentParser` 相同的 :meth:`~ArgumentParser.add_argument` 方法。當引數被加" "入群組時,剖析器會像處理正常引數一樣處理它,但在說明訊息中以獨立的群組顯示該" "引數。:meth:`!add_argument_group` 方法接受 *title* 和 *description* 引數,可" "以用來自訂此顯示: ::" #: ../../library/argparse.rst:1973 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" ">>> group1 = parser.add_argument_group('group1', 'group1 description')\n" ">>> group1.add_argument('foo', help='foo help')\n" ">>> group2 = parser.add_argument_group('group2', 'group2 description')\n" ">>> group2.add_argument('--bar', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [--bar BAR] foo\n" "\n" "group1:\n" " group1 description\n" "\n" " foo foo help\n" "\n" "group2:\n" " group2 description\n" "\n" " --bar BAR bar help" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" ">>> group1 = parser.add_argument_group('group1', 'group1 description')\n" ">>> group1.add_argument('foo', help='foo help')\n" ">>> group2 = parser.add_argument_group('group2', 'group2 description')\n" ">>> group2.add_argument('--bar', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [--bar BAR] foo\n" "\n" "group1:\n" " group1 description\n" "\n" " foo foo help\n" "\n" "group2:\n" " group2 description\n" "\n" " --bar BAR bar help" #: ../../library/argparse.rst:1991 msgid "" "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 :class:" "`ArgumentParser` constructor, but apply specifically to the argument group " "rather than the entire parser." msgstr "" "選擇性的僅限關鍵字參數 argument_default_ 和 conflict_handler_ 允許對引數群組" "的行為進行更精細的控制。這些參數的意義與 :class:`ArgumentParser` 建構函式中的" "相同,但專門適用於引數群組而非整個剖析器。" #: ../../library/argparse.rst:1996 msgid "" "Note that any arguments not in your user-defined groups will end up back in " "the usual \"positional arguments\" and \"optional arguments\" sections." msgstr "" "請注意,任何不在使用者定義群組中的引數會歸入一般的「位置引數」和「可選引數」" "區段。" #: ../../library/argparse.rst:1999 msgid "" "Within each argument group, arguments are displayed in help output in the " "order in which they are added." msgstr "" #: ../../library/argparse.rst:2002 msgid "" "Calling :meth:`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." msgstr "" "在引數群組上呼叫 :meth:`add_argument_group` 現在會引發例外。這種巢狀用法從未" "被支援,通常無法正確運作,是因為繼承而無意間被公開出來的。" #: ../../library/argparse.rst:2007 msgid "Passing prefix_chars_ to :meth:`add_argument_group` is now deprecated." msgstr "將 prefix_chars_ 傳給 :meth:`add_argument_group` 的用法現在已棄用。" #: ../../library/argparse.rst:2013 msgid "Mutual exclusion" msgstr "互斥" #: ../../library/argparse.rst:2017 msgid "" "Create a mutually exclusive group. :mod:`!argparse` will make sure that only " "one of the arguments in the mutually exclusive group was present on the " "command line::" msgstr "" "建立一個互斥群組。:mod:`!argparse` 會確保互斥群組中只有一個引數出現在命令列" "上: ::" #: ../../library/argparse.rst:2021 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> group = parser.add_mutually_exclusive_group()\n" ">>> group.add_argument('--foo', action='store_true')\n" ">>> group.add_argument('--bar', action='store_false')\n" ">>> parser.parse_args(['--foo'])\n" "Namespace(bar=True, foo=True)\n" ">>> parser.parse_args(['--bar'])\n" "Namespace(bar=False, foo=False)\n" ">>> parser.parse_args(['--foo', '--bar'])\n" "usage: PROG [-h] [--foo | --bar]\n" "PROG: error: argument --bar: not allowed with argument --foo" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> group = parser.add_mutually_exclusive_group()\n" ">>> group.add_argument('--foo', action='store_true')\n" ">>> group.add_argument('--bar', action='store_false')\n" ">>> parser.parse_args(['--foo'])\n" "Namespace(bar=True, foo=True)\n" ">>> parser.parse_args(['--bar'])\n" "Namespace(bar=False, foo=False)\n" ">>> parser.parse_args(['--foo', '--bar'])\n" "usage: PROG [-h] [--foo | --bar]\n" "PROG: error: argument --bar: not allowed with argument --foo" #: ../../library/argparse.rst:2033 msgid "" "The :meth:`add_mutually_exclusive_group` method also accepts a *required* " "argument, to indicate that at least one of the mutually exclusive arguments " "is required::" msgstr "" ":meth:`add_mutually_exclusive_group` 方法也接受一個 *required* 引數,用來指示" "至少需要一個互斥引數: ::" #: ../../library/argparse.rst:2037 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> group = parser.add_mutually_exclusive_group(required=True)\n" ">>> group.add_argument('--foo', action='store_true')\n" ">>> group.add_argument('--bar', action='store_false')\n" ">>> parser.parse_args([])\n" "usage: PROG [-h] (--foo | --bar)\n" "PROG: error: one of the arguments --foo --bar is required" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> group = parser.add_mutually_exclusive_group(required=True)\n" ">>> group.add_argument('--foo', action='store_true')\n" ">>> group.add_argument('--bar', action='store_false')\n" ">>> parser.parse_args([])\n" "usage: PROG [-h] (--foo | --bar)\n" "PROG: error: one of the arguments --foo --bar is required" #: ../../library/argparse.rst:2045 msgid "" "Note that currently mutually exclusive argument groups do not support the " "*title* and *description* arguments of :meth:`~ArgumentParser." "add_argument_group`. However, a mutually exclusive group can be added to an " "argument group that has a title and description. For example::" msgstr "" "請注意,目前互斥引數群組不支援 :meth:`~ArgumentParser.add_argument_group` 的 " "*title* 和 *description* 引數。然而互斥群組可以加入到具有標題和描述的引數群組" "中。例如: ::" #: ../../library/argparse.rst:2051 msgid "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> group = parser.add_argument_group('Group title', 'Group description')\n" ">>> exclusive_group = group.add_mutually_exclusive_group(required=True)\n" ">>> exclusive_group.add_argument('--foo', help='foo help')\n" ">>> exclusive_group.add_argument('--bar', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [-h] (--foo FOO | --bar BAR)\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "Group title:\n" " Group description\n" "\n" " --foo FOO foo help\n" " --bar BAR bar help" msgstr "" ">>> parser = argparse.ArgumentParser(prog='PROG')\n" ">>> group = parser.add_argument_group('Group title', 'Group description')\n" ">>> exclusive_group = group.add_mutually_exclusive_group(required=True)\n" ">>> exclusive_group.add_argument('--foo', help='foo help')\n" ">>> exclusive_group.add_argument('--bar', help='bar help')\n" ">>> parser.print_help()\n" "usage: PROG [-h] (--foo FOO | --bar BAR)\n" "\n" "options:\n" " -h, --help show this help message and exit\n" "\n" "Group title:\n" " Group description\n" "\n" " --foo FOO foo help\n" " --bar BAR bar help" #: ../../library/argparse.rst:2068 msgid "" "Calling :meth:`add_argument_group` or :meth:`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." msgstr "" "在互斥群組上呼叫 :meth:`add_argument_group` 或 :meth:" "`add_mutually_exclusive_group` 現在會引發例外。這種巢狀用法從未支援,通常無法" "正確運作,且是因為繼承而無意間被公開出來的。" #: ../../library/argparse.rst:2076 msgid "Parser defaults" msgstr "剖析器預設值" #: ../../library/argparse.rst:2080 msgid "" "Most of the time, the attributes of the object returned by :meth:" "`parse_args` will be fully determined by inspecting the command-line " "arguments and the argument actions. :meth:`set_defaults` allows some " "additional attributes that are determined without any inspection of the " "command line to be added::" msgstr "" "在大多數情況下,:meth:`parse_args` 回傳物件的屬性會完全由檢查命令列引數和引" "數 action 來決定。:meth:`set_defaults` 允許加入一些無需檢查命令列即可決定的額" "外屬性: ::" #: ../../library/argparse.rst:2086 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('foo', type=int)\n" ">>> parser.set_defaults(bar=42, baz='badger')\n" ">>> parser.parse_args(['736'])\n" "Namespace(bar=42, baz='badger', foo=736)" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('foo', type=int)\n" ">>> parser.set_defaults(bar=42, baz='badger')\n" ">>> parser.parse_args(['736'])\n" "Namespace(bar=42, baz='badger', foo=736)" #: ../../library/argparse.rst:2092 msgid "" "Note that defaults can be set at both the parser level using :meth:" "`set_defaults` and at the argument level using :meth:`add_argument`. If both " "are called for the same argument, the last default set for an argument is " "used::" msgstr "" "請注意,預設值可以在剖析器層級使用 :meth:`set_defaults` 設定,也可以在引數層" "級使用 :meth:`add_argument` 設定。如果兩者都為同一個引數呼叫,會使用最後設定" "的預設值: ::" #: ../../library/argparse.rst:2096 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default='bar')\n" ">>> parser.set_defaults(foo='spam')\n" ">>> parser.parse_args([])\n" "Namespace(foo='spam')" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default='bar')\n" ">>> parser.set_defaults(foo='spam')\n" ">>> parser.parse_args([])\n" "Namespace(foo='spam')" #: ../../library/argparse.rst:2102 msgid "" "Parser-level defaults can be particularly useful when working with multiple " "parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an " "example of this type." msgstr "" "在使用多個剖析器時,剖析器層級的預設值可能特別有用。請參閱 :meth:" "`~ArgumentParser.add_subparsers` 方法以了解這類範例。" #: ../../library/argparse.rst:2108 msgid "" "Get the default value for a namespace attribute, as set by either :meth:" "`~ArgumentParser.add_argument` or by :meth:`~ArgumentParser.set_defaults`::" msgstr "" "取得命名空間屬性的預設值,由 :meth:`~ArgumentParser.add_argument` 或 :meth:" "`~ArgumentParser.set_defaults` 設定: ::" #: ../../library/argparse.rst:2112 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default='badger')\n" ">>> parser.get_default('foo')\n" "'badger'" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', default='badger')\n" ">>> parser.get_default('foo')\n" "'badger'" #: ../../library/argparse.rst:2119 msgid "Printing help" msgstr "印出幫助訊息" #: ../../library/argparse.rst:2121 msgid "" "In most typical applications, :meth:`~ArgumentParser.parse_args` will take " "care of formatting and printing any usage or error messages. However, " "several formatting methods are available:" msgstr "" "在大多數典型的應用程式中,:meth:`~ArgumentParser.parse_args` 會處理格式化和印" "出任何用法或錯誤訊息。然而,有幾個格式化方法可以使用:" #: ../../library/argparse.rst:2127 msgid "" "Print a brief description of how the :class:`ArgumentParser` should be " "invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is " "assumed." msgstr "" "印出 :class:`ArgumentParser` 在命令列上呼叫方式的簡短描述。如果 *file* 為 " "``None``,則假設為 :data:`sys.stdout`。" #: ../../library/argparse.rst:2133 msgid "" "Print a help message, including the program usage and information about the " "arguments registered with the :class:`ArgumentParser`. If *file* is " "``None``, :data:`sys.stdout` is assumed." msgstr "" "印出說明訊息,包括程式用法和在 :class:`ArgumentParser` 中註冊的引數相關資訊。" "如果 *file* 為 ``None``,假設為 :data:`sys.stdout`。" #: ../../library/argparse.rst:2137 msgid "" "There are also variants of these methods that simply return a string instead " "of printing it:" msgstr "這些方法也有變體,它們只回傳字串而非印出它:" #: ../../library/argparse.rst:2142 msgid "" "Return a string containing a brief description of how the :class:" "`ArgumentParser` should be invoked on the command line." msgstr "" "回傳一個字串,包含 :class:`ArgumentParser` 在命令列上的呼叫方式的簡短描述。" #: ../../library/argparse.rst:2147 msgid "" "Return a string containing a help message, including the program usage and " "information about the arguments registered with the :class:`ArgumentParser`." msgstr "" "回傳一個字串,包含說明訊息,包括程式用法和在 :class:`ArgumentParser` 中註冊的" "引數相關資訊。" #: ../../library/argparse.rst:2152 msgid "Partial parsing" msgstr "部分剖析" #: ../../library/argparse.rst:2156 msgid "" "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 :meth:`~ArgumentParser.parse_known_args` method can be " "useful." msgstr "" "有時候一個腳本只需要處理特定的一組命令列引數,將任何未辨識的引數留給另一個腳" "本或程式。在這些情況下,:meth:`~ArgumentParser.parse_known_args` 方法可能很有" "用。" #: ../../library/argparse.rst:2161 msgid "" "This method works similarly to :meth:`~ArgumentParser.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." msgstr "" "此方法的運作方式類似 :meth:`~ArgumentParser.parse_args`,但它不會對額外的、未" "辨識的引數引發錯誤,而是會只剖析已知的引數並回傳一個包含填充後的命名空間和任" "何未辨識引數串列的二元素元組。" #: ../../library/argparse.rst:2168 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='store_true')\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])\n" "(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo', action='store_true')\n" ">>> parser.add_argument('bar')\n" ">>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])\n" "(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])" #: ../../library/argparse.rst:2175 msgid "" ":ref:`Prefix matching ` rules apply to :meth:" "`~ArgumentParser.parse_known_args`. The parser may consume an option even if " "it's just a prefix of one of its known options, instead of leaving it in the " "remaining arguments list." msgstr "" ":ref:`前綴匹配 `\\ 規則適用於 :meth:`~ArgumentParser." "parse_known_args`。即使選項只是其已知選項之一的前綴,剖析器也可能消耗它,而非" "將其留在剩餘引數串列中。" #: ../../library/argparse.rst:2182 msgid "Customizing file parsing" msgstr "自訂檔案剖析" #: ../../library/argparse.rst:2186 msgid "" "Arguments that are read from a file (see the *fromfile_prefix_chars* keyword " "argument to the :class:`ArgumentParser` constructor) are read one argument " "per line. :meth:`convert_arg_line_to_args` can be overridden for fancier " "reading." msgstr "" "從檔案讀取的引數(請參閱 :class:`ArgumentParser` 建構函式的 " "*fromfile_prefix_chars* 關鍵字引數)每行讀取一個引數。可以覆寫 :meth:" "`convert_arg_line_to_args` 以進行更精細的讀取。" #: ../../library/argparse.rst:2191 msgid "" "This method takes a single argument *arg_line* which is a string read from " "the argument file. It returns a list of arguments parsed from this string. " "The method is called once per line read from the argument file, in order." msgstr "" "此方法接受單個引數 *arg_line*,它是從引數檔案讀取的字串。它回傳從此字串剖析出" "的引數串列。此方法對從引數檔案讀取的每一行依序呼叫一次。" #: ../../library/argparse.rst:2195 msgid "" "A useful override of this method is one that treats each space-separated " "word as an argument. The following example demonstrates how to do this::" msgstr "" "此方法的一個有用覆寫是將每個以空格分隔的詞作為引數。以下範例示範了如何做到這" "一點: ::" #: ../../library/argparse.rst:2198 msgid "" "class MyArgumentParser(argparse.ArgumentParser):\n" " def convert_arg_line_to_args(self, arg_line):\n" " return arg_line.split()" msgstr "" "class MyArgumentParser(argparse.ArgumentParser):\n" " def convert_arg_line_to_args(self, arg_line):\n" " return arg_line.split()" #: ../../library/argparse.rst:2204 msgid "Exiting methods" msgstr "退出方法" #: ../../library/argparse.rst:2208 msgid "" "This method terminates the program, exiting with the specified *status* and, " "if given, it prints a *message* to :data:`sys.stderr` before that. The user " "can override this method to handle these steps differently::" msgstr "" "此方法終止程式,以指定的 *status* 退出,並在退出前(如果有提供的話)向 :data:" "`sys.stderr` 印出一個 *message*。使用者可以覆寫此方法來以不同方式處理這些步" "驟: ::" #: ../../library/argparse.rst:2212 msgid "" "class ErrorCatchingArgumentParser(argparse.ArgumentParser):\n" " def exit(self, status=0, message=None):\n" " if status:\n" " raise Exception(f'Exiting because of an error: {message}')\n" " exit(status)" msgstr "" "class ErrorCatchingArgumentParser(argparse.ArgumentParser):\n" " def exit(self, status=0, message=None):\n" " if status:\n" " raise Exception(f'Exiting because of an error: {message}')\n" " exit(status)" #: ../../library/argparse.rst:2220 msgid "" "This method prints a usage message, including the *message*, to :data:`sys." "stderr` and terminates the program with a status code of 2." msgstr "" "此方法將用法訊息(包含 *message*)印出到 :data:`sys.stderr`,並以狀態碼 2 終" "止程式。" #: ../../library/argparse.rst:2225 msgid "Intermixed parsing" msgstr "交錯剖析" #: ../../library/argparse.rst:2230 msgid "" "A number of Unix commands allow the user to intermix optional arguments with " "positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args` " "and :meth:`~ArgumentParser.parse_known_intermixed_args` methods support this " "parsing style." msgstr "" "許多 Unix 命令允許使用者將可選引數與位置引數交錯使用。:meth:`~ArgumentParser." "parse_intermixed_args` 和 :meth:`~ArgumentParser." "parse_known_intermixed_args` 方法支援此剖析風格。" #: ../../library/argparse.rst:2235 msgid "" "These parsers do not support all the :mod:`!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." msgstr "" "這些剖析器不支援所有 :mod:`!argparse` 功能,如果使用了不支援的功能會引發例" "外。特別是不支援子剖析器,以及同時包含可選引數和位置引數的互斥群組。" #: ../../library/argparse.rst:2240 msgid "" "The following example shows the difference between :meth:`~ArgumentParser." "parse_known_args` and :meth:`~ArgumentParser.parse_intermixed_args`: the " "former returns ``['2', '3']`` as unparsed arguments, while the latter " "collects all the positionals into ``rest``. ::" msgstr "" "以下範例展示了 :meth:`~ArgumentParser.parse_known_args` 和 :meth:" "`~ArgumentParser.parse_intermixed_args` 之間的差異:前者回傳 ``['2', '3']`` " "作為未剖析的引數,而後者將所有位置引數收集到 ``rest`` 中。 ::" #: ../../library/argparse.rst:2246 msgid "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> parser.add_argument('cmd')\n" ">>> parser.add_argument('rest', nargs='*', type=int)\n" ">>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())\n" "(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])\n" ">>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())\n" "Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])" msgstr "" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.add_argument('--foo')\n" ">>> parser.add_argument('cmd')\n" ">>> parser.add_argument('rest', nargs='*', type=int)\n" ">>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())\n" "(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])\n" ">>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())\n" "Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])" #: ../../library/argparse.rst:2255 msgid "" ":meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple " "containing the populated namespace and the list of remaining argument " "strings. :meth:`~ArgumentParser.parse_intermixed_args` raises an error if " "there are any remaining unparsed argument strings." msgstr "" ":meth:`~ArgumentParser.parse_known_intermixed_args` 回傳一個二元素元組,包含" "填充後的命名空間和剩餘引數字串的串列。:meth:`~ArgumentParser." "parse_intermixed_args` 在有任何剩餘未剖析的引數字串時會引發錯誤。" #: ../../library/argparse.rst:2264 msgid "Registering custom types or actions" msgstr "註冊自訂型別或 action" #: ../../library/argparse.rst:2268 msgid "" "Sometimes it's desirable to use a custom string in error messages to provide " "more user-friendly output. In these cases, :meth:`!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." msgstr "" "有時候想要在錯誤訊息中使用自訂字串以提供更友善的輸出。在這些情況下,可以使" "用 :meth:`!register` 向剖析器註冊自訂 action 或型別,讓你可以透過註冊名稱而非" "可呼叫物件名稱來參照型別。" #: ../../library/argparse.rst:2273 msgid "" "The :meth:`!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." msgstr "" ":meth:`!register` 方法接受三個引數——*registry_name*,指定用於儲存物件的內部登" "錄檔(例如 ``action``、``type``);*value*,用於註冊物件的鍵值;以及 object," "要註冊的可呼叫物件。" #: ../../library/argparse.rst:2278 msgid "" "The following example shows how to register a custom type with a parser::" msgstr "以下範例展示如何向剖析器註冊自訂型別: ::" #: ../../library/argparse.rst:2280 msgid "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.register('type', 'hexadecimal integer', lambda s: int(s, 16))\n" ">>> parser.add_argument('--foo', type='hexadecimal integer')\n" "_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)\n" ">>> parser.parse_args(['--foo', '0xFA'])\n" "Namespace(foo=250)\n" ">>> parser.parse_args(['--foo', '1.2'])\n" "usage: PROG [-h] [--foo FOO]\n" "PROG: error: argument --foo: invalid 'hexadecimal integer' value: '1.2'" msgstr "" ">>> import argparse\n" ">>> parser = argparse.ArgumentParser()\n" ">>> parser.register('type', 'hexadecimal integer', lambda s: int(s, 16))\n" ">>> parser.add_argument('--foo', type='hexadecimal integer')\n" "_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)\n" ">>> parser.parse_args(['--foo', '0xFA'])\n" "Namespace(foo=250)\n" ">>> parser.parse_args(['--foo', '1.2'])\n" "usage: PROG [-h] [--foo FOO]\n" "PROG: error: argument --foo: invalid 'hexadecimal integer' value: '1.2'" #: ../../library/argparse.rst:2292 msgid "Exceptions" msgstr "例外" #: ../../library/argparse.rst:2296 msgid "An error from creating or using an argument (optional or positional)." msgstr "建立或使用引數(可選或位置引數)時的錯誤。" #: ../../library/argparse.rst:2298 msgid "" "The string value of this exception is the message, augmented with " "information about the argument that caused it." msgstr "此例外的字串值是訊息,附帶了導致錯誤的引數的相關資訊。" #: ../../library/argparse.rst:2303 msgid "" "Raised when something goes wrong converting a command line string to a type." msgstr "當將命令列字串轉換為型別時出錯時引發。" #: ../../library/argparse.rst:2307 msgid "Guides and Tutorials" msgstr "指南與教學" #: ../../library/argparse.rst:908 msgid "? (question mark)" msgstr "? (問號)" #: ../../library/argparse.rst:908 ../../library/argparse.rst:940 #: ../../library/argparse.rst:954 msgid "in argparse module" msgstr "於 argparse 模組中" #: ../../library/argparse.rst:940 msgid "* (asterisk)" msgstr "* (星號)" #: ../../library/argparse.rst:954 msgid "+ (plus)" msgstr "+ (加號)"