argparse

https://docs.python.org/3/library/argparse.html

 
使用步骤:
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  argparse. ArgumentParser( prog=Noneusage=Nonedescription=Noneepilog=Noneparents=[]formatter_class=argparse.HelpFormatterprefix_chars='-'fromfile_prefix_chars=Noneargument_default=Noneconflict_handler='error'add_help=Trueallow_abbrev=True)

Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:

  • prog - The name of the program (default: sys.argv[0])
  • usage - The string describing the program usage (default: generated from arguments added to parser)
  • description - Text to display before the argument help (default: none)
  • epilog - Text to display after the argument help (default: none)
  • parents - A list of ArgumentParser objects whose arguments should also be included
  • formatter_class - A class for customizing the help output
  • prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)
  • fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
  • argument_default - The global default value for arguments (default: None)
  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
  • add_help - Add a -h/--help option to the parser (default: True)
  • allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

Changed in version 3.5: allow_abbrev parameter was added.

 

 

2. The add_argument() method

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

Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
  • action - The basic type of action to be taken when this argument is encountered at the command line.
  • nargs - The number of command-line arguments that should be consumed.
  • const - A constant value required by some action and nargs selections.
  • default - The value produced if the argument is absent from the command line.
  • type - The type to which the command-line argument should be converted.
  • choices - A container of the allowable values for the argument.
  • required - Whether or not the command-line option may be omitted (optionals only).
  • help - A brief description of what the argument does.
  • metavar - A name for the argument in usage messages.
  • dest - The name of the attribute to be added to the object returned by parse_args().
 
 
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里面

2.3. nargs
>>> 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_argsargs = Nonenamespace = 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)

 

转载于:https://www.cnblogs.com/shenfr/p/10111161.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值