详解Python中argpasrse模块的基本使用

编程技术圈

共 5085字,需浏览 11分钟

 · 2020-07-10

3063288dcdb61e212d39fc1b84903e95.webpdeb02549adfc98f85a429f0d165ebd41.webp

点击蓝字关注我们

51f12501d57be76ae9662c10f8a12259.webp


9507fe9fd067466d9bcbe2c9b26493f7.webp2d917596fba9d247744450a72dad09a2.webp


argpasrse模块的使用


import  argparseparser = argparse.ArgumentParser(    prog = 'ls',    description='Process some int',    add_help = True)parser.add_argument('path',nargs='?', default='.', help='file path')# 位置参数parser.add_argument('-l',dest='list', action='store_true')parser.add_argument('-a', '--all', action='store_true')

args = parser.parse_args() # 解析:如:/etc ---> e t c 把其当作一个可迭代对象了,所以可以这样输入 ('/etc',)parser.print_help() # windows 使用这个调试print('-------------------------------------')print( args.all, args.list, args.path) #None None /etc

在win下,模拟插入位置参数,如 /etc 可以在run-->Edit configuration下或者在:args = parser.parse_args('/etc')



① 默认会打印帮助信息,默认提供 '''


py文件:

import  argparseparser = argparse.ArgumentParser(description='Process some int')args = parser.parse_args()parser.print_help() # windows  使用这个调试


打印信息:

usage: homework_解析_9-4.py [-h]
Process some int
optional arguments: -h, --help show this help message and exit



② ArgumentParser下的内容


def __init__(self,prog=None,描述程序的,sys.args[0]也就是输入的命令, 如:a.pyusage=None,程序使用方式description=None,epilog=None,parents=[],formatter_class=HelpFormatter,prefix_chars='-',fromfile_prefix_chars=None,argument_default=None, 缺省值conflict_handler='error',add_help=True,默认的帮助信息,-h,--help Fals表示取消allow_abbrev=True):



③ 取消help


import  argparseparser = argparse.ArgumentParser(    prog = 'ls',  # 给命令起个名字 ls    description='Process some int',    add_help = False # 改为False)args = parser.parse_args()parser.print_help() # windows  使用这个调试


打印信息:

usage: ls
Process some int


没有取消的信息:

usage: ls [-h] # 中括号表示可选,linux特色
Process some int
optional arguments:  -h, --help  show this help message and exit



④ 必须提供参数,也就是说执行ls.py的时候,后面要跟 路径 如:/etc


import  argparseparser = argparse.ArgumentParser(    prog = 'ls',    description='Process some int',    add_help = True)parser.add_argument('path')#


打印信息:

args = parser.parse_args()usage: ls [-h] pathls: error: the following arguments are required: path



⑤ 长选项


import  argparseparser = argparse.ArgumentParser(    prog = 'ls',    description='Process some int',    add_help = True)parser.add_argument('path')parser.add_argument('-l')parser.add_argument('-a','--all')
args = parser.parse_args()


打印信息:

usage: ls [-h] [-l L] [-a ALL] path
Process some int
positional arguments: path
optional arguments: -h, --help show this help message and exit -l L  -a ALL, --all ALL



⑥ namespace,sys.argv[1:],没有提供 ,就是None,提供了,则传到namespace


import  argparseparser = argparse.ArgumentParser(    prog = 'ls',    description='Process some int',    add_help = True)parser.add_argument('path')parser.add_argument('-l')parser.add_argument('-a','--all')
args = parser.parse_args(('/etc',)) # 解析:如:/etc ---> e t c 把其当作一个可迭代对象了,所以可以这样输入 ('/etc',)parser.print_help() # windows 使用这个调试print(args)


打印信息:

usage: ls [-h] [-l L] [-a ALL] path
Process some int
positional arguments: path
optional arguments: -h, --help show this help message and exit -l L -a ALL, --all ALLNamespace(all=None, l=None, path='/etc')



⑦ 获取参数对应的属性的值 ,通过namespace,但是参数如果有--all这样的,只能用args.all'''


args = parser.parse_args('/etc'.split()) # 解析:如:/etc ---> e t c  把其当作一个可迭代对象了,所以可以这样输入 ('/etc',)print( args.all, args.l, args.path) #None None /etc


打印信息:

None None /etc



⑧ -l -a 默认必须带参,如何不带参'''


帮助文档:

    add_argument() method         •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.         •dest - The name of the attribute to be added to the object returned by parse_args().parser.add_argument('path',nargs='?')# 位置参数打印:usage: ls [-h] [-l L] [-a ALL] [path] 此时path 加中括号了,可有可无
parser.add_argument('path',nargs='?', default='.')# 位置参数,加了一个默认值,当前目录
#### ? 表示可有可无,+ 至少一个,*可以任意个,数字表示必须指定数目
parser.add_argument('-l', action='store_true') # 不需要传参了


打印信息:

usage: ls [-h] [-l] [-a ALL] [path]         parser.add_argument('-l', action='store_true')args = parser.parse_args('-l'.split()) print( args.all, args.l, args.path) 


打印信息:

因为store_true,所以给了 -l 则打印true,否则为 false

如果store_false,不给-l 就打印true

parser.add_argument('-l', action='store_const', const=23)args = parser.parse_args('-l'.split()) 


打印信息:

如果给了,就打印 23,不给,打印None



⑨ 每个命令提供一个help信息 '''


parser.add_argument('path',nargs='?', default='.', help='file path')# 位置参数


打印信息:

  path        file path



⑩ 给namespace的属性提供一个方便使用的名字,如args.l 使用args.list'''

parser.add_argument('-l',dest='list', action='store_true')print( args.all, args.list, args.path) #None None /etc


打印信息:

False False . 

这个名字只是在namespace中用,不会影响命令调用时的 -l




   - end -  


微信号 : coding_club

● 扫码关注我们

觉得内容还不错的话,给我点个“在看”呗

ff9c8a7c9a1a5be9ddb8063384e46b00.webp
54d0fcb24f7920f857b83b42b0062019.webp



浏览 49
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报