python 模块argparse用法实例详解

简介:  argparse是python内置模块,用于快速创建命令行。有一个第三方模块Click也可以实现这个功能,两者各有优缺点,看个人需求吧。官方网页https://docs.python.
+关注继续查看

 argparse是python内置模块,用于快速创建命令行。有一个第三方模块Click也可以实现这个功能,两者各有优缺点,看个人需求吧。


官方网页

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

import  argparse
__version__ = '1.1.1'
parser = argparse.ArgumentParser(description='hahahaaaa')
parser.add_argument('-V', '--version', action='version', version='%(prog)s '+__version__)
parser.add_argument('--name','-n',metavar='namemma',dest='name',type=str,help='your name',nargs=1)
parser.add_argument('-i',metavar='III',action='store_const',dest='iiii',const='ii',help="dfafsdf")
parser.add_argument("-z", choices=['a', 'b', 'd'],required=False)
parser.add_argument('foo')
args = parser.parse_args()

print(type(args))
print(args.name,args.iiii,args.foo)

ArgumentParser参数的简单说明

 epilog - 命令行帮助的结尾文字 

 prog - (default: sys.argv[0])程序的名字,一般不需要修改,另外,如果你需要在help中使用到程序的名字,可以使用%(prog)s

 prefix_chars - 命令的前缀,默认是-,例如-f/--file。有些程序可能希望支持/f这样的选项,可以使用prefix_chars="/"

 fromfile_prefix_chars - (default: None)如果你希望命令行参数可以从文件中读取,就可能用到。例如,如果fromfile_prefix_chars='@',命令行参数中有一个为"@args.txt",args.txt的内容会作为命令行参数

 add_help - 是否增加-h/-help选项(default:True),一般help信息都是必须的,所以不用设置啦。

 

add_argument:读入命令行参数,该调用有多个参数

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

name or flags:是必须的参数,该参数接受选项参数或者是位置参数(一串文件名)


不带'--'的参数

    调用脚本时必须输入值

    参数输入的顺序与程序中定义的顺序一致

'-'的参数

    可不输入    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)

    metavar: 参数的名字,在显示 帮助信息时才用到.

    action:

        store:默认action模式,存储值到指定变量。

        store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。

        store_true / store_false:布尔开关。可以2个参数对应一个变量。

        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:通常-f这样的选项是可选的,但是如果required=True那么就是必须的了

    nsrgs 用来指定参数的个数,可以是1,2,3....也可以是?或*或+

        ? 零个或一个

        * 零个或多个

        + 一个或多个


创建子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()


目录
相关文章
|
3天前
|
Python
跟我从0学Python——函数和模块
第三篇:函数和模块 —— 代码的模块化与重用
|
5天前
|
SQL JSON 关系型数据库
Python 使用SQLAlchemy数据库模块
SQLAlchemy 是用Python编程语言开发的一个开源项目,它提供了SQL工具包和ORM对象关系映射工具,使用MIT许可证发行,SQLAlchemy 提供高效和高性能的数据库访问,实现了完整的企业级持久模型。ORM(对象关系映射)是一种编程模式,用于将对象与关系型数据库中的表和记录进行映射,从而实现通过面向对象的方式进行数据库操作。ORM 的目标是在编程语言中使用类似于面向对象编程的语法,而不是使用传统的 SQL 查询语言,来操作数据库。
|
6天前
|
人工智能 Python
AI Earth在本地安装相关模块时,确实需要关注Python的版本
AI Earth在本地安装相关模块时,确实需要关注Python的版本
32 2
|
9天前
|
Python
python 父级兄弟路径 导入模块
python 父级兄弟路径 导入模块
17 0
|
14天前
|
数据挖掘 Python
Python如何使用Matplotlib模块的pie()函数绘制饼形图?
Python如何使用Matplotlib模块的pie()函数绘制饼形图?
18 0
|
16天前
|
Python Windows
Python 扩展 快捷贴士:os模块下的创建目录的方式
如果子目录创建失败或者已经存在,会抛出一个 OSError 的异常,Windows上Error 183 即为目录已经存在的异常错误。
13 0
|
16天前
|
Python
Python 关于模块的几点介绍 。和。。和__all__和__main___和__file__
用来定义我们导出的内容可以有哪些的一个编码方式
11 0
|
17天前
|
Python
Python用于解析和修改文本数据-pyparsing模块教程
Python用于解析和修改文本数据-pyparsing模块教程
25 0
|
19天前
|
Ubuntu Python
Python 记录在Ubuntu上的一次模块缺失的摸排检查工作
记录在Ubuntu上的一次模块缺失的摸排检查工作
16 0
|
21天前
|
JSON Linux 开发工具
linux 利用python模块实现格式化json
linux 利用python模块实现格式化json
17 0
推荐文章
更多