python中的argparse模块(参数解析)

import argparse
parse = argparse.ArgumentParser()
parse.add_argument("a", help="params means")
parse.add_argument("-C", "--gc", default="count")
parse.add_argument("--ga", help="params means ga",dest='simple_value',choices=['A', 'B', 'C', 0])
parse.add_argument("--gb", help="params means gb",action="store_const",const='value-to-store')
args = parse.parse_args()
print args.simple_value,args.gb,args.gc

### add_argument 说明
不带'--'的参数
    调用脚本时必须输入值
    参数输入的顺序与程序中定义的顺序一致
'-'的参数
    可不输入    add_argument("-a")
    类似有'--'的shortname,但程序中的变量名为定义的参数名
'--'参数
    参数别名: 只能是1个字符,区分大小写
        add_argument("-shortname","--name", help="params means"),但代码中不能使用shortname
    dest: 参数在程序中对应的变量名称 add_argument("a",dest='code_name')
    default: 参数默认值
    help: 参数作用解释  add_argument("a", help="params means")
    type : 默认string  add_argument("c", type=int)
    action:
    store:默认action模式,存储值到指定变量。
    store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。
    store_true / store_false:布尔开关。 store_true.默认为False,输入则为true。 store_flase 相反
    append:存储值到列表,该参数可以重复使用。
    append_const:存储值到列表,存储值在参数的const部分指定。
    count: 统计参数简写输入的个数  add_argument("-c", "--gc", action="count")
    version 输出版本信息然后退出。
    const:配合action="store_const|append_const"使用,默认值
    choices:输入值的范围 add_argument("--gb", choices=['A', 'B', 'C', 0])
    required : 默认False, 若为 True, 表示必须输入该参数


==================================================================================
    Keyword Arguments:
        - option_strings -- A list of command-line option strings which    should be associated with this action.
        - dest -- The name of the attribute to hold the created object(s)
        - nargs -- The number of command-line arguments that should be  consumed. By default, one argument will be consumed and a single   value will be produced.
                     Other values include:
                - N (an integer) consumes N arguments (and produces a list)
                - '?' consumes zero or one arguments
                - '*' consumes zero or more arguments (and produces a list)
                - '+' consumes one or more arguments (and produces a list)
                    Note that the difference between the default and nargs=1 is that with the default, a single value will be produced, while with  nargs=1, a list containing a single value will be produced.
        - const -- The value to be produced if the option is specified and the  option uses an action that takes no values.
        - default -- The value to be produced if the option is not specified.
        - type -- A callable that accepts a single string argument, and returns the converted value.  
                    The standard Python types str, int,  float, and complex are useful examples of such callables.  If None,  str is used.
        - choices -- A container of values that should be allowed.
                    If not None,  after a command-line argument has been converted to the appropriate type, an exception will be raised if it is not a member of this collection.
        - required -- True if the action must always be specified at the command line. This is only meaningful for optional command-line  arguments.
        - help -- The help string describing the argument.
        - metavar -- The name to be used for the option's argument with the  help string. If None, the 'dest' value will be used as the name.


  • 创建子parse,每个子parse对应自己的输入参数

  

点击(此处)折叠或打开

import argparse

# sub-command functions

def subcmd_list(args):
   print "list"

def subcmd_create(args):

   print "create"

def subcmd_delete(args):

   print "delete"

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help='commands')

# A list command
list_parser = subparsers.add_parser('list', help='Listcontents')
list_parser.add_argument('dirname', action='store', help='Directory tolist')
list_parse.set_defaults(func=subcmd_list)

# A create command
create_parser = subparsers.add_parser('create', help='Create a directory')
create_parser.add_argument('dirname',action='store',help='New directoryto create')
create_parser.add_argument('--read-only',default=False, action='store_true',help='Setpermissions to prevent writing to the directory')
create_parser .set_defaults(func=subcmd_create)


# A delete command
delete_parser = subparsers.add_parser('delete',help='Remove a directory')
delete_parser.add_argument( 'dirname', action='store',help='The directory to remove')
delete_parser.add_argument('--recursive', '-r',default=False, action='store_true',help='Remove thecontents of the directory, too')
delete_parser .set_defaults(func=subcmd_delete)

args = parser.parse_args()
# call subcmd
args.fun(args)


使用帮助
# python args_subparse.py -h
usage: args_subparse.py [-h] {create,list,delete} ...

positional arguments:
  {create,list,delete}  commands
    list                Listcontents
    create              Create a directory
    delete              Remove a directory

optional arguments:
  -h, --help            show this help message and exit
  
# python args_subparse.py create -h
usage: args_subparse.py create [-h] [--read-only] dirname

positional arguments:
  dirname      New directoryto create

optional arguments:
  -h, --help   show this help message and exit
  --read-only  Setpermissions to prevent writing to the directory
  
# python args_subparse.py delete -h
usage: args_subparse.py delete [-h] [--recursive] dirname

positional arguments:
  dirname          The directory to remove

optional arguments:
  -h, --help       show this help message and exit
  --recursive, -r  Remove thecontents of the directory, too
 
# python args_subparse.py list -h
usage: args_subparse.py list [-h] dirname

positional arguments:
  dirname     Directory tolist

optional arguments:
  -h, --help  show this help message and exit


多个subparser 使用同样定义的参数
# add_help=False,必须指定,否则报-h重复定义
parents_parser = argparse.ArgumentParser(add_help=False)
parents_parser.add_argument('--foo', dest="foo", action='store_true')
parents_parser.add_argument('--bar', dest="bar", action='store_false')
parents_parser.add_argument('--baz', dest="baz", action='store_false')

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='commands')
m_parser = subparsers.add_parser("mysql", parents=[parents_parser], help="mysql method")
m_parser.set_defaults(func=sub_mysql)
o_parser = subparsers.add_parser("oracle", parents=[parents_parser], help="oracle method")
o_parser.set_defaults(func=sub_oracle)
args = parser.parse_args()



参考
http://blog.csdn.net/songuooo/article/details/8373086
http://www.2cto.com/kf/201208/149418.html
http://stackoverflow.com/questions/7498595/python-argparse-add-argument-to-multiple-subparsers
  • 6
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: argparsePython标准库的一个命令行解析模块。它可以自动生成帮助和使用信息,并且支持默认值、可选参数、位置参数等。 下面是一个简单的使用argparse的例子: ```python import argparse parser = argparse.ArgumentParser(description='A simple argparse example') parser.add_argument('-n', '--name', type=str, help='Your name') parser.add_argument('-a', '--age', type=int, help='Your age') args = parser.parse_args() print('Hello,', args.name, 'your age is', args.age) ``` 运行上面的代码后,可以通过命令行来传入参数,如: ``` python test.py -n John -a 30 ``` 这样就能在程序得到参数name和age的值,输出: ``` Hello, John your age is 30 ``` argparse模块还支持其他选项,如添加默认值、设置参数为可选或必选等,详见官方文档。 ### 回答2: argparsePython的一个命令行参数解析模块。它可以用来解析命令行参数以及生成用于帮助文档的用户友好的提示信息。 使用argparse模块可以轻松定义和解析命令行参数。下面是一个argparse的简单实例: 假设我们要编写一个程序来计算两个数字的和。我们希望能够从命令行传递这两个数字作为参数,并且能够选择是否将计算结果打印出来。 首先,我们需要导入argparse模块,然后创建一个ArgumentParser对象: import argparse parser = argparse.ArgumentParser() 然后,我们可以使用add_argument()方法来定义我们需要的参数parser.add_argument("num1", type=int, help="第一个数字") parser.add_argument("num2", type=int, help="第二个数字") parser.add_argument("-p", "--print", action="store_true", help="打印计算结果") 在这个例子,我们使用add_argument()方法定义了两个位置参数num1和num2,分别表示第一个数字和第二个数字。我们还使用了一个可选参数--print(简写为-p),用来表示是否打印计算结果。action="store_true"表示如果命令行指定了--print参数,则将其存储为True,否则为False。 接下来,我们需要使用parse_args()方法来解析命令行参数: args = parser.parse_args() 现在,我们可以使用args对象来访问用户输入参数了: sum_result = args.num1 + args.num2 if args.print: print("计算结果:", sum_result) 最后,我们可以将上述代码保存为一个Python脚本文件,然后在命令行运行该文件,并传递两个数字和可选的--print参数来测试程序的功能,例如: python calculator.py 2 3 --print 以上就是argparse模块解析和实例的简单介绍。这个模块非常灵活和强大,可以用于处理各种类型的命令行参数,包括位置参数、可选参数、默认值等等。它还可以生成用户友好的帮助文档,以方便用户使用程序。 ### 回答3: Pythonargparse模块是一个用于解析命令行参数的库。它可以帮助我们在命令行传递参数,并且提供了一些额外的功能,比如生成帮助信息和错误提示。 使用argparse模块非常简单。我们首先需要导入argparse库,然后创建一个ArgumentParser对象。然后,我们可以使用add_argument()方法来添加我们需要的命令行参数add_argument()方法有很多参数可以配置,比如name或flags指定参数的名称,type指定参数的类型,default指定参数的默认值等等。我们可以根据我们的具体需求来配置这些参数。 当命令行参数被定义后,我们可以通过parse_args()方法来解析命令行参数。这个方法会返回一个包含解析后的参数的命名空间对象,我们可以使用这个对象的属性来访问具体的参数值。 下面是一个使用argparse模块的简单示例: ```python import argparse # 创建ArgumentParser对象 parser = argparse.ArgumentParser(description='这是一个解析命令行参数的示例') # 添加命令行参数 parser.add_argument('name', type=str, help='你的名字') parser.add_argument('age', type=int, help='你的年龄') # 解析命令行参数 args = parser.parse_args() # 访问参数值 print('你好,{},你的年龄是{}岁。'.format(args.name, args.age)) ``` 在上面的示例,我们创建了一个ArgumentParser对象,并添加了两个命令行参数:name和age。然后我们解析命令行参数,并使用args对象访问参数值并打印出来。 当我们在命令行运行这个脚本时,我们需要在脚本名称后面提供两个参数,即我们的名字和年龄。比如: ``` $ python script.py Alice 25 ``` 这样,脚本就会打印出:`你好,Alice,你的年龄是25岁。`

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值