日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:argparse—-命令行選項、參數(shù)和子命令解析器

argparse —- 命令行選項、參數(shù)和子命令解析器

3.2 新版功能.

源代碼: Lib/argparse.py


教程

此頁面包含該 API 的參考信息。有關(guān) python 命令行解析更細致的介紹,請參閱 argparse 教程。

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

Core Functionality

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

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

The ArgumentParser.add_argument() method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:

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

The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object:

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

Quick Links for add_argument()

Name

Description

Values

action

Specify how an argument should be handled

‘store’, ‘store_const’, ‘store_true’, ‘a(chǎn)ppend’, ‘a(chǎn)ppend_const’, ‘count’, ‘help’, ‘version’

choices

Limit values to a specific set of choices

[‘foo’, ‘bar’], range(1, 10), or Container instance

const

Store a constant value

default

Default value used when an argument is not provided

Defaults to None

dest

Specify the attribute name used in the result namespace

help

Help message for an argument

metavar

Alternate display name for the argument as shown in help

nargs

Number of times the argument can be used

int, ‘?’, ‘*’, ‘+’, or argparse.REMAINDER

required

Indicate whether an argument is required or optional

True or False

type

Automatically convert an argument to the given type

int, float, argparse.FileType(‘w’), or callable function

示例

以下代碼是一個 Python 程序,它獲取一個整數(shù)列表并計算總和或者最大值:

 
 
 
 
  1. import argparse
  2. parser = argparse.ArgumentParser(description='Process some integers.')
  3. parser.add_argument('integers', metavar='N', type=int, nargs='+',
  4. help='an integer for the accumulator')
  5. parser.add_argument('--sum', dest='accumulate', action='store_const',
  6. const=sum, default=max,
  7. help='sum the integers (default: find the max)')
  8. args = parser.parse_args()
  9. print(args.accumulate(args.integers))

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

 
 
 
 
  1. $ python prog.py -h
  2. usage: prog.py [-h] [--sum] N [N ...]
  3. Process some integers.
  4. positional arguments:
  5. N an integer for the accumulator
  6. options:
  7. -h, --help show this help message and exit
  8. --sum sum the integers (default: find the max)

當(dāng)使用適當(dāng)?shù)膮?shù)運行時,它會輸出命令行傳入整數(shù)的總和或者最大值:

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

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

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

以下部分將引導(dǎo)你完成這個示例。

創(chuàng)建一個解析器

使用 argparse 的第一步是創(chuàng)建一個 ArgumentParser 對象:

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

ArgumentParser 對象包含將命令行解析成 Python 數(shù)據(jù)類型所需的全部信息。

添加參數(shù)

給一個 ArgumentParser 添加程序參數(shù)信息是通過調(diào)用 add_argument() 方法完成的。通常,這些調(diào)用指定 ArgumentParser 如何獲取命令行字符串并將其轉(zhuǎn)換為對象。這些信息在 parse_args() 調(diào)用時被存儲和使用。例如:

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

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

解析參數(shù)

ArgumentParser 通過 parse_args() 方法解析參數(shù)。它將檢查命令行,把每個參數(shù)轉(zhuǎn)換為適當(dāng)?shù)念愋腿缓笳{(diào)用相應(yīng)的操作。在大多數(shù)情況下,這意味著一個簡單的 Namespace 對象將從命令行解析出的屬性構(gòu)建:

 
 
 
 
  1. >>> parser.parse_args(['--sum', '7', '-1', '42'])
  2. Namespace(accumulate=, integers=[7, -1, 42])

在腳本中,通常 parse_args() 會被不帶參數(shù)調(diào)用,而 ArgumentParser 將自動從 sys.argv 中確定命令行參數(shù)。

ArgumentParser 對象

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

創(chuàng)建一個新的 ArgumentParser 對象。所有的參數(shù)都應(yīng)當(dāng)作為關(guān)鍵字參數(shù)傳入。每個參數(shù)在下面都有它更詳細的描述,但簡而言之,它們是:

  • prog - 程序的名稱 (默認值: os.path.basename(sys.argv[0]))

  • usage - 描述程序用途的字符串(默認值:從添加到解析器的參數(shù)生成)

  • description - Text to display before the argument help (by default, no text)

  • epilog - Text to display after the argument help (by default, no text)

  • parents - 一個 ArgumentParser 對象的列表,它們的參數(shù)也應(yīng)包含在內(nèi)

  • formatter_class - 用于自定義幫助文檔輸出格式的類

  • prefix_chars - 可選參數(shù)的前綴字符集合(默認值: ‘-‘)

  • fromfile_prefix_chars - 當(dāng)需要從文件中讀取其他參數(shù)時,用于標(biāo)識文件名的前綴字符集合(默認值: None

  • argument_default - 參數(shù)的全局默認值(默認值: None

  • conflict_handler - 解決沖突選項的策略(通常是不必要的)

  • add_help - 為解析器添加一個 -h/--help 選項(默認值: True

  • allow_abbrev - 如果縮寫是無歧義的,則允許縮寫長選項 (默認值:True

  • exit_on_error - 決定當(dāng)錯誤發(fā)生時是否讓 ArgumentParser 附帶錯誤信息退出。 (默認值: True)

在 3.5 版更改: 增加了 allow_abbrev 參數(shù)。

在 3.8 版更改: 在之前的版本中,allow_abbrev 還會禁用短旗標(biāo)分組,例如 -vv 表示為 -v -v

在 3.9 版更改: 添加了 exit_on_error 形參。

以下部分描述這些參數(shù)如何使用。

prog

默認情況下,ArgumentParser 對象使用 sys.argv[0] 來確定如何在幫助消息中顯示程序名稱。這一默認值幾乎總是可取的,因為它將使幫助消息與從命令行調(diào)用此程序的方式相匹配。例如,對于有如下代碼的名為 myprogram.py 的文件:

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

該程序的幫助信息將顯示 myprogram.py 作為程序名稱(無論程序從何處被調(diào)用):

 
 
 
 
  1. $ python myprogram.py --help
  2. usage: myprogram.py [-h] [--foo FOO]
  3. options:
  4. -h, --help show this help message and exit
  5. --foo FOO foo help
  6. $ cd ..
  7. $ python subdir/myprogram.py --help
  8. usage: myprogram.py [-h] [--foo FOO]
  9. options:
  10. -h, --help show this help message and exit
  11. --foo FOO foo help

要更改這樣的默認行為,可以使用 prog= 參數(shù)為 ArgumentParser 指定另一個值:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='myprogram')
  2. >>> parser.print_help()
  3. usage: myprogram [-h]
  4. options:
  5. -h, --help show this help message and exit

需要注意的是,無論是從 sys.argv[0] 或是從 prog= 參數(shù)確定的程序名稱,都可以在幫助消息里通過 %(prog)s 格式說明符來引用。

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='myprogram')
  2. >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
  3. >>> parser.print_help()
  4. usage: myprogram [-h] [--foo FOO]
  5. options:
  6. -h, --help show this help message and exit
  7. --foo FOO foo of the myprogram program

usage

默認情況下,ArgumentParser 根據(jù)它包含的參數(shù)來構(gòu)建用法消息:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('--foo', nargs='?', help='foo help')
  3. >>> parser.add_argument('bar', nargs='+', help='bar help')
  4. >>> parser.print_help()
  5. usage: PROG [-h] [--foo [FOO]] bar [bar ...]
  6. positional arguments:
  7. bar bar help
  8. options:
  9. -h, --help show this help message and exit
  10. --foo [FOO] foo help

可以通過 usage= 關(guān)鍵字參數(shù)覆蓋這一默認消息:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
  2. >>> parser.add_argument('--foo', nargs='?', help='foo help')
  3. >>> parser.add_argument('bar', nargs='+', help='bar help')
  4. >>> parser.print_help()
  5. usage: PROG [options]
  6. positional arguments:
  7. bar bar help
  8. options:
  9. -h, --help show this help message and exit
  10. --foo [FOO] foo help

在用法消息中可以使用 %(prog)s 格式說明符來填入程序名稱。

description

大多數(shù)對 ArgumentParser 構(gòu)造方法的調(diào)用都會使用 description= 關(guān)鍵字參數(shù)。 這個參數(shù)簡要描述這個程序做什么以及怎么做。 在幫助消息中,這個描述會顯示在命令行用法字符串和各種參數(shù)的幫助消息之間:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(description='A foo that bars')
  2. >>> parser.print_help()
  3. usage: argparse.py [-h]
  4. A foo that bars
  5. options:
  6. -h, --help show this help message and exit

在默認情況下,description 將被換行以便適應(yīng)給定的空間。如果想改變這種行為,見 formatter_class 參數(shù)。

epilog

一些程序喜歡在 description 參數(shù)后顯示額外的對程序的描述。這種文字能夠通過給 ArgumentParser:: 提供 epilog= 參數(shù)而被指定。

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(
  2. ... description='A foo that bars',
  3. ... epilog="And that's how you'd foo a bar")
  4. >>> parser.print_help()
  5. usage: argparse.py [-h]
  6. A foo that bars
  7. options:
  8. -h, --help show this help message and exit
  9. And that's how you'd foo a bar

和 description 參數(shù)一樣,epilog= text 在默認情況下會換行,但是這種行為能夠被調(diào)整通過提供 formatter_class 參數(shù)給 ArgumentParse.

parents

有些時候,少數(shù)解析器會使用同一系列參數(shù)。 單個解析器能夠通過提供 parents= 參數(shù)給 ArgumentParser 而使用相同的參數(shù)而不是重復(fù)這些參數(shù)的定義。parents= 參數(shù)使用 ArgumentParser 對象的列表,從它們那里收集所有的位置和可選的行為,然后將這寫行為加到正在構(gòu)建的 ArgumentParser 對象。

 
 
 
 
  1. >>> parent_parser = argparse.ArgumentParser(add_help=False)
  2. >>> parent_parser.add_argument('--parent', type=int)
  3. >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
  4. >>> foo_parser.add_argument('foo')
  5. >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
  6. Namespace(foo='XXX', parent=2)
  7. >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
  8. >>> bar_parser.add_argument('--bar')
  9. >>> bar_parser.parse_args(['--bar', 'YYY'])
  10. Namespace(bar='YYY', parent=None)

請注意大多數(shù)父解析器會指定 add_help=False . 否則, ArgumentParse 將會看到兩個 -h/--help 選項(一個在父參數(shù)中一個在子參數(shù)中)并且產(chǎn)生一個錯誤。

備注

你在通過``parents=`` 傳遞解析器之前必須完全初始化它們。 如果你在子解析器之后改變父解析器,這些改變將不會反映在子解析器上。

formatter_class

ArgumentParser 對象允許通過指定備用格式化類來自定義幫助格式。目前,有四種這樣的類。

class argparse.RawDescriptionHelpFormatter

class argparse.RawTextHelpFormatter

class argparse.ArgumentDefaultsHelpFormatter

class argparse.MetavarTypeHelpFormatter

RawDescriptionHelpFormatter 和 RawTextHelpFormatter 在正文的描述和展示上給與了更多的控制。ArgumentParser 對象會將 description 和 epilog 的文字在命令行中自動換行。

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... description='''this description
  4. ... was indented weird
  5. ... but that is okay''',
  6. ... epilog='''
  7. ... likewise for this epilog whose whitespace will
  8. ... be cleaned up and whose words will be wrapped
  9. ... across a couple lines''')
  10. >>> parser.print_help()
  11. usage: PROG [-h]
  12. this description was indented weird but that is okay
  13. options:
  14. -h, --help show this help message and exit
  15. likewise for this epilog whose whitespace will be cleaned up and whose words
  16. will be wrapped across a couple lines

傳 RawDescriptionHelpFormatter 給 formatter_class= 表示 description 和 epilog 已經(jīng)被正確的格式化了,不能在命令行中被自動換行:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... formatter_class=argparse.RawDescriptionHelpFormatter,
  4. ... description=textwrap.dedent('''\
  5. ... Please do not mess up this text!
  6. ... --------------------------------
  7. ... I have indented it
  8. ... exactly the way
  9. ... I want it
  10. ... '''))
  11. >>> parser.print_help()
  12. usage: PROG [-h]
  13. Please do not mess up this text!
  14. --------------------------------
  15. I have indented it
  16. exactly the way
  17. I want it
  18. options:
  19. -h, --help show this help message and exit

RawTextHelpFormatter 保留所有種類文字的空格,包括參數(shù)的描述。然而,多重的新行會被替換成一行。如果你想保留多重的空白行,可以在新行之間加空格。

ArgumentDefaultsHelpFormatter 自動添加默認的值的信息到每一個幫助信息的參數(shù)中:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  4. >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
  5. >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
  6. >>> parser.print_help()
  7. usage: PROG [-h] [--foo FOO] [bar ...]
  8. positional arguments:
  9. bar BAR! (default: [1, 2, 3])
  10. options:
  11. -h, --help show this help message and exit
  12. --foo FOO FOO! (default: 42)

MetavarTypeHelpFormatter 為它的值在每一個參數(shù)中使用 type 的參數(shù)名當(dāng)作它的顯示名(而不是使用通常的格式 dest ):

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... formatter_class=argparse.MetavarTypeHelpFormatter)
  4. >>> parser.add_argument('--foo', type=int)
  5. >>> parser.add_argument('bar', type=float)
  6. >>> parser.print_help()
  7. usage: PROG [-h] [--foo int] float
  8. positional arguments:
  9. float
  10. options:
  11. -h, --help show this help message and exit
  12. --foo int

prefix_chars

許多命令行會使用 - 當(dāng)作前綴,比如 -f/--foo。如果解析器需要支持不同的或者額外的字符,比如像 +f 或者 /foo 的選項,可以在參數(shù)解析構(gòu)建器中使用 prefix_chars= 參數(shù)。

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

prefix_chars= 參數(shù)默認使用 '-'。 提供一組不包括 - 的字符將導(dǎo)致 -f/--foo 選項不被允許。

fromfile_prefix_chars

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

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

從文件讀取的參數(shù)在默認情況下必須一個一行(但是可參見 convert_arg_line_to_args())并且它們被視為與命令行上的原始文件引用參數(shù)位于同一位置。所以在以上例子中,['-f', 'foo', '@args.txt'] 的表示和 ['-f', 'foo', '-f', 'bar'] 的表示相同。

fromfile_prefix_chars= 參數(shù)默認為 None,意味著參數(shù)不會被當(dāng)作文件對待。

argument_default

一般情況下,參數(shù)默認會通過設(shè)置一個默認到 add_argument() 或者調(diào)用帶一組指定鍵值對的 ArgumentParser.set_defaults() 方法。但是有些時候,為參數(shù)指定一個普遍適用的解析器會更有用。這能夠通過傳輸 argument_default= 關(guān)鍵詞參數(shù)給 ArgumentParser 來完成。舉個栗子,要全局禁止在 parse_args() 中創(chuàng)建屬性,我們提供 argument_default=SUPPRESS:

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

allow_abbrev

正常情況下,當(dāng)你向 ArgumentParser 的 parse_args() 方法傳入一個參數(shù)列表時,它會 recognizes abbreviations。

這個特性可以設(shè)置 allow_abbrevFalse 來關(guān)閉:

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

3.5 新版功能.

conflict_handler

ArgumentParser 對象不允許在相同選項字符串下有兩種行為。默認情況下, ArgumentParser 對象會產(chǎn)生一個異常如果去創(chuàng)建一個正在使用的選項字符串參數(shù)。

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

有些時候(例如:使用 parents),重寫舊的有相同選項字符串的參數(shù)會更有用。為了產(chǎn)生這種行為, 'resolve' 值可以提供給 ArgumentParser 的 conflict_handler= 參數(shù):

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
  2. >>> parser.add_argument('-f', '--foo', help='old foo help')
  3. >>> parser.add_argument('--foo', help='new foo help')
  4. >>> parser.print_help()
  5. usage: PROG [-h] [-f FOO] [--foo FOO]
  6. options:
  7. -h, --help show this help message and exit
  8. -f FOO old foo help
  9. --foo FOO new foo help

注意 ArgumentParser 對象只能移除一個行為如果它所有的選項字符串都被重寫。所以,在上面的例子中,舊的 -f/--foo 行為 回合 -f 行為保持一樣, 因為只有 --foo 選項字符串被重寫。

add_help

默認情況下,ArgumentParser 對象添加一個簡單的顯示解析器幫助信息的選項。舉個栗子,考慮一個名為 myprogram.py 的文件包含如下代碼:

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

如果 -h or --help 在命令行中被提供, 參數(shù)解析器幫助信息會打印:

 
 
 
 
  1. $ python myprogram.py --help
  2. usage: myprogram.py [-h] [--foo FOO]
  3. options:
  4. -h, --help show this help message and exit
  5. --foo FOO foo help

有時候可能會需要關(guān)閉額外的幫助信息。這可以通過在 ArgumentParser 中設(shè)置 add_help= 參數(shù)為 False 來實現(xiàn)。

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
  2. >>> parser.add_argument('--foo', help='foo help')
  3. >>> parser.print_help()
  4. usage: PROG [--foo FOO]
  5. options:
  6. --foo FOO foo help

幫助選項一般為 -h/--help。如果 prefix_chars= 被指定并且沒有包含 - 字符,在這種情況下, -h --help 不是有效的選項。此時, prefix_chars 的第一個字符將用作幫助選項的前綴。

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
  2. >>> parser.print_help()
  3. usage: PROG [+h]
  4. options:
  5. +h, ++help show this help message and exit

exit_on_error

正常情況下,當(dāng)你向 ArgumentParser 的 parse_args() 方法傳入一個無效的參數(shù)列表時,它將會退出并發(fā)出錯誤信息。

如果用戶想要手動捕獲錯誤,可通過將 exit_on_error 設(shè)為 False 來啟用該特性:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(exit_on_error=False)
  2. >>> parser.add_argument('--integers', type=int)
  3. _StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=, choices=None, help=None, metavar=None)
  4. >>> try:
  5. ... parser.parse_args('--integers a'.split())
  6. ... except argparse.ArgumentError:
  7. ... print('Catching an argumentError')
  8. ...
  9. Catching an argumentError

3.9 新版功能.

add_argument() 方法

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

定義單個的命令行參數(shù)應(yīng)當(dāng)如何解析。每個形參都在下面有它自己更多的描述,長話短說有:

  • name or flags - 一個命名或者一個選項字符串的列表,例如 foo-f, --foo。

  • action - 當(dāng)參數(shù)在命令行中出現(xiàn)時使用的動作基本類型。

  • nargs - 命令行參數(shù)應(yīng)當(dāng)消耗的數(shù)目。

  • const - 被一些 action 和 nargs 選擇所需求的常數(shù)。

  • default - 當(dāng)參數(shù)未在命令行中出現(xiàn)并且也不存在于命名空間對象時所產(chǎn)生的值。

  • type - 命令行參數(shù)應(yīng)當(dāng)被轉(zhuǎn)換成的類型。

  • choices - 可用的參數(shù)的容器。

  • required - 此命令行選項是否可省略 (僅選項可用)。

  • help - 一個此選項作用的簡單描述。

  • metavar - 在使用方法消息中使用的參數(shù)值示例。

  • dest - 被添加到 parse_args() 所返回對象上的屬性名。

以下部分描述這些參數(shù)如何使用。

name or flags

The 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 add_argument() must therefore be either a series of flags, or a simple argument name.

For example, an optional argument could be created like:

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

而位置參數(shù)可以這么創(chuàng)建:

 
 
 
 
  1. >>> parser.add_argument('bar')

當(dāng) parse_args() 被調(diào)用,選項會以 - 前綴識別,剩下的參數(shù)則會被假定為位置參數(shù):

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('-f', '--foo')
  3. >>> parser.add_argument('bar')
  4. >>> parser.parse_args(['BAR'])
  5. Namespace(bar='BAR', foo=None)
  6. >>> parser.parse_args(['BAR', '--foo', 'FOO'])
  7. Namespace(bar='BAR', foo='FOO')
  8. >>> parser.parse_args(['--foo', 'FOO'])
  9. usage: PROG [-h] [-f FOO] bar
  10. PROG: error: the following arguments are required: bar

action

ArgumentParser 對象將命令行參數(shù)與動作相關(guān)聯(lián)。這些動作可以做與它們相關(guān)聯(lián)的命令行參數(shù)的任何事,盡管大多數(shù)動作只是簡單的向 parse_args() 返回的對象上添加屬性。action 命名參數(shù)指定了這個命令行參數(shù)應(yīng)當(dāng)如何處理。供應(yīng)的動作有:

  • 'store' - 存儲參數(shù)的值。這是默認的動作。例如:

       
       
       
       
    1. >>> parser = argparse.ArgumentParser()
    2. >>> parser.add_argument('--foo')
    3. >>> parser.parse_args('--foo 1'.split())
    4. Namespace(foo='1')
  • '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:

       
       
       
       
    1. >>> parser = argparse.ArgumentParser()
    2. >>> 網(wǎng)頁題目:創(chuàng)新互聯(lián)Python教程:argparse—-命令行選項、參數(shù)和子命令解析器
      文章網(wǎng)址:http://www.5511xx.com/article/cdcehds.html