使用步骤:
import argparse
parser= argparse.ArgumentParser(description="test the argparse!")
parser. add_argument('--username',default=None,help='username of Github')
parser. parse_args()
1. ArgumentParser objects
- class
-
Create a new object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:
- - The name of the program (default:
sys.argv[0]
) - - The string describing the program usage (default: generated from arguments added to parser)
- - Text to display before the argument help (default: none)
- - Text to display after the argument help (default: none)
- - A list of objects whose arguments should also be included
- - A class for customizing the help output
- - The set of characters that prefix optional arguments (default: ‘-‘)
- - The set of characters that prefix files from which additional arguments should be read (default:
None
) - - The global default value for arguments (default:
None
) - - The strategy for resolving conflicting optionals (usually unnecessary)
- - Add a
-h/--help
option to the parser (default:True
) - - Allows long options to be abbreviated if the abbreviation is unambiguous. (default:
True
)
Changed in version 3.5: allow_abbrev parameter was added.
- - The name of the program (default:
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)
2. The add_argument() method
-
Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:
- - Either a name or a list of option strings, e.g.
foo
or-f, --foo
. - - The basic type of action to be taken when this argument is encountered at the command line.
- - The number of command-line arguments that should be consumed.
- - A constant value required by some and selections.
- - The value produced if the argument is absent from the command line.
- - The type to which the command-line argument should be converted.
- - A container of the allowable values for the argument.
- - Whether or not the command-line option may be omitted (optionals only).
- - A brief description of what the argument does.
- - A name for the argument in usage messages.
- - The name of the attribute to be added to the object returned by .
- - Either a name or a list of option strings, e.g.
ArgumentParser.
add_argument
( name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) 2.1. 位置参数
前面不加-或--
2.2. action
>>> parser.add_argument('--foo', action='store_true')注:加上--foo,那么foo=True, 不加--foo,那么foo=False>>> parser.add_argument('--foo', action='store_const', const=42) 注:加上--foo,那么foo=42, 不加--foo,那么foo=None>>> parser.add_argument('--foo', action='append')>>> parser.parse_args('--foo 1 --foo 2'.split()) Namespace(foo=['1', '2'])注:多次指定foo,把参数扩展到foo list里面
>>> parser.add_argument('--foo', nargs=2) >>> parser.add_argument('bar', nargs=1)>>> parser.parse_args('c --foo a b'.split())Namespace(bar=['c'], foo=['a', 'b']) 注:设置nargs=1和不设置 返回的结果是不同的,nargs=2 表示后面接两个参数,并将两个参数放列表里面 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')>>> parser.add_argument('bar', nargs='?', default='d')>>> parser.parse_args(['XX', '--foo', 'YY'])Namespace(bar='XX', foo='YY')>>> parser.parse_args(['XX', '--foo'])Namespace(bar='XX', foo='c')>>> parser.parse_args([])Namespace(bar='d', foo='d')注:nargs='?', const='c', default='d' 三个一起使用 意思是:脚本执行时, 若不加--foo,则foo=default的值; 若单独加--foo,则foo=const的值; 若--foo YY,则foo=YY
2.4. choices
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])>>> parser.add_argument('door', type=int, choices=range(1, 4))>>> parser.parse_args('paper 3'.split())Namespace(door=3, move='paper')注:参数的值只能从choices面选择
2.5. required
>>> parser.add_argument('--foo', required=True)>>> parser.parse_args(['--foo', 'BAR'])Namespace(foo='BAR')注:脚本执行时没有相应的参数会报错
3. The parse_args() method
ArgumentParser.
parse_args
( args = None, namespace = None ) 将参数字符串转换为对象并将其指定为命名空间的属性。返回填充的命名空间。 4. vars
>>> parser.add_argument('--foo')>>> args = parser.parse_args(['--foo', 'haha'])>>> parser.add_argument('--int', type=int)>>> args=parser.parse_args(['--foo','haha','--int','4'])>>> vars(args){ 'foo': 'haha', 'int': 4}注:返回的是一个字典
5. Sub-commands
>>> # create the top-level parser>>> parser = argparse.ArgumentParser(prog='PROG')>>> parser.add_argument('--foo', action='store_true', help='foo help')>>> subparsers = parser.add_subparsers(help='sub-command help')>>>>>> # create the parser for the "a" command>>> parser_a = subparsers.add_parser('a', help='a help')>>> parser_a.add_argument('bar', type=int, help='bar help')>>>>>> # create the parser for the "b" command>>> parser_b = subparsers.add_parser('b', help='b help')>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')>>>>>> # parse some argument lists>>> parser.parse_args(['a', '12'])Namespace(bar=12, foo=False)>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])Namespace(baz='Z', foo=True)