参考资料:

https://www.youtube.com/watch?v=cdblJqEUDNo&t=298s

不方便用梯子的也可以看B站:

Python argparse命令行参数解析包的详细使用说明书_哔哩哔哩_bilibili

以下是argparse笔记:

用法三步走:

①创建一个装参数的容器。

②往容器里面添加参数。

③解析容器里面的参数。

1.positional argument

特点:

①参数名前面没有横杠。

②不同的参数,输入的先后顺序不能改变。

③运行的时候不能输入参数名(输入参数名会报错),只需输入参数值。即:

python 文件名 参数值1 参数值2

以计算圆柱体积的代码为例。新建demo1.py。

import math
import argparseparser = argparse.ArgumentParser(description='Calculate volume of a Cylinder')
parser.add_argument('radius', type=int, help='Radius of Cylinder')
parser.add_argument('height', type=int, help='Height of Cylinder')
args = parser.parse_args()def cylinder_volume(radius, height):vol = (math.pi) * (radius ** 2) * (height)return volif __name__ == '__main__':print (cylinder_volume(args.radius, args.height))

查看帮助信息,在终端输入:

python demo1.py -h

终端显示:

usage: demo1.py [-h] radius heightCalculate volume of a Cylinder    #parser定义的时候,description里面的内容positional arguments:radius      Radius of Cylinderheight      Height of Cylinderoptional arguments:-h, --help  show this help message and exit

计算  radius=2    height=4 的圆柱体积:

python demo1.py 2 4

结果:

50.26548245743669

交换一下参数输入的顺序:

python demo1.py 4 2

结果:

100.53096491487338
#计算的是 radius=4 height=2的圆柱体积

2.optional argument

特点:

①参数名之前有横杠。

②运行的时候要带参数值。即

python 文件名 参数名1 参数值1 参数名2 参数值2...

③参数值可以交换顺序,对运行结果没有影响。即

python 文件名 参数名2 参数值2 参数名1 参数值1 ...

④因为输入的参数值可以交换顺序,所以输入的时候必须带上参数名,否则报错。

新建demo2.py

import math
import argparseparser = argparse.ArgumentParser(description='Calculate volume of a Cylinder')
parser.add_argument('--radius', type=int, help='Radius of Cylinder')#注意双横杠!
parser.add_argument('--height', type=int, help='Height of Cylinder')
args = parser.parse_args()def cylinder_volume(radius, height):vol = (math.pi) * (radius ** 2) * (height)return volif __name__ == '__main__':print (cylinder_volume(args.radius, args.height))

查看帮助信息:

python demo2.py -h

显示

usage: demo2.py [-h] [--radius RADIUS] [--height HEIGHT]Calculate volume of a Cylinderoptional arguments:-h, --help       show this help message and exit--radius RADIUS  Radius of Cylinder    #有横杠之后变成可选参数了!--height HEIGHT  Height of Cylinder

计算  radius=2    height=4 的圆柱体积:

python demo2.py --radius 2 --height 4

或者:

python demo2.py --height 4 --radius 2

输出都是 半径为2 高度为4 的圆柱体的体积!

50.26548245743669

注意,因为前面参数定义的时候是:

--radius  --height

所以后面参数调用的地方是:

args.radius  args.height

一定要对应起来哦!

不过每次都输入这么长的参数名太麻烦了,那就在参数定义的地方,再另外输入一个以单横杠开头的,简写的参数名。即:

parser.add_argument('-r', '--radius', type=int, help='Radius of Cylinder')

或者:

parser.add_argument('--radius', '-r',type=int, help='Radius of Cylinder')

--radius和-r完全等价,顺序可以交换,只需要注意,真正的参数名以双横杠开头,简写的参数名以单横杠开头。

把height这个参数也改一下。

parser.add_argument('-H', '--height', type=int, help='Height of Cylinder')

大写-H是因为,小写的-h已经被 帮助 占用啦!

计算  radius=2    height=4 的圆柱体积,以下八种参数输入方式完全等价:

python demo2.py -r 2 -H 4python demo2.py -H 4 -r 2python demo2.py --radius 2 --height 4python demo2.py --height 4 --radius 2python demo2.py --radius 2 -H 4python demo2.py --H 4 --radius 2python demo2.py -r 2 --height 4python demo2.py --height 4 -r 2

输出都是:

50.26548245743669

再来完善一下~

help信息显示得有点乱,-r 后面紧跟的是RADIUS。

usage: demo2.py [-h] [-r RADIUS] [-H HEIGHT]Calculate volume of a Cylinderoptional arguments:-h, --help            show this help message and exit-r RADIUS, --radius RADIUSRadius of Cylinder-H HEIGHT, --height HEIGHTHeight of Cylinder

在添加参数的时候,写上metavar等于空字符串,就把原来的RADIUS  HEIGHT这些替换为空字符串了。上代码:

parser.add_argument('-r', '--radius', type=int, metavar='', help='Radius of Cylinder')
parser.add_argument('-H', '--height', type=int, metavar='', help='Height of Cylinder')

metavar=空字符串 也可以写在其他位置,只要写在参数名'-r', '--radius'之后即可。比如:

parser.add_argument('-r', '--radius', type=int, help='Radius of Cylinder', metavar='')
parser.add_argument('-H', '--height', type=int, metavar='', help='Height of Cylinder')

现在的help信息变得很整齐:

usage: demo2.py [-h] [-r] [-H]Calculate volume of a Cylinderoptional arguments:-h, --help      show this help message and exit-r , --radius   Radius of Cylinder-H , --height   Height of Cylinder

如果运行代码的时候少输入了一个参数,那么会默认它是None,就会报错。比如:

python demo2.py -r 2

报错:

Traceback (most recent call last):File "/home/yukey/Documents/NLP_Code_All/argparse参数解析/demo2.py", line 22, in <me>print (cylinder_volume(args.radius, args.height))File "/home/yukey/Documents/NLP_Code_All/argparse参数解析/demo2.py", line 18, in cyer_volumevol = (math.pi) * (radius ** 2) * (height)
TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'

在添加参数的时候写上required=True,当缺少该参数的时候就会有提示了。同样地,required=True写在参数名后面的任意位置都可以。

parser.add_argument('-r', '--radius', type=int, help='Radius of Cylinder', metavar='', required=True)
parser.add_argument('-H', '--height', required=True, type=int, metavar='', help='Height of Cylinder')

输入:

python demo2.py -r 2

提示:

usage: demo2.py [-h] -r  -H
demo2.py: error: the following arguments are required: -H/--height

3.mutually exclusive group

互斥组,字面上理解就是一组参数,里面的参数关系是互斥的,只能有一个True,其余为False。

下面以设置三种输出格式为例,这三种情况是互斥的。

①quiet:只输出一个数字。

②verbose:输出很啰嗦的一串说明文字+数字。

③不指定互斥参数:输出一句话+数字。

新建demo3.py 上代码:

import math
import argparseparser = argparse.ArgumentParser(description='Calculate volume of a Cylinder')
parser.add_argument('-r', '--radius', required=True, type=int, metavar='', help='Radius of Cylinder')
parser.add_argument('-H', '--height', required=True, type=int, metavar='', help='Height of Cylinder')
group = parser.add_mutually_exclusive_group()
group.add_argument('-q', '--quiet', action='store_true', help='print quiet')
group.add_argument('-v', '--verbose', action='store_true', help='print verbose')
args = parser.parse_args()def cylinder_volume(radius, height):vol = (math.pi) * (radius ** 2) * (height)return volif __name__ == '__main__':volume = cylinder_volume(args.radius, args.height)if args.quiet:    #指定-qprint(volume)elif args.verbose:    #指定-vprint("Volume of a Cylinder with radius %s and height %s and height %s is %s" % (args.radius, args.height, volume))else:    #既不指定-q 也不指定-vprint("Volume of Cylinder = %s" % volume)

注意,新添加的group这个容器是在原来的parser的基础上再add mutually exclusive group,而不是另起炉灶!

其中action='store_true'的意思是,指定这个参数的时候,该参数就是True。博主的原话是:When you give it an action,it stores true. The default become False。

显示一下帮助信息:

python demo3.py -h

帮助信息如下:

usage: demo3.py [-h] -r  -H  [-q | -v]Calculate volume of a Cylinderoptional arguments:-h, --help      show this help message and exit-r , --radius   Radius of Cylinder-H , --height   Height of Cylinder-q, --quiet     print quiet-v, --verbose   print verbose

指定-q:

python demo3.py -r 2 -H 4 -q

输出:

50.26548245743669

指定-v:

python demo3.py -r 2 -H 4 -v

输出:

Volume of a Cylinder with radius 2 and height 4 and height is 50.26548245743669

既不指定-q 也不指定-v:

python demo3.py -r 2 -H 4 

输出:

Volume of Cylinder = 50.26548245743669

python的argparse参数解析相关推荐

  1. python命令行参数解析OptionParser类用法实例

    python命令行参数解析OptionParser类用法实例 本文实例讲述了python命令行参数解析OptionParser类的用法,分享给大家供大家参考. 具体代码如下:     from opt ...

  2. Python命令行参数解析模块getopt使用实例

    这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参考下 格式 getopt(args, options ...

  3. Python命令行参数解析

    Python命令行参数解析 Python命令行解析是指读取终端传入的参数 sys.argv属性 这个是sys库立面的一个属性,其用于接收传入程序的命令行参数.它是一个列表.也就是差不多下面这种类型 s ...

  4. Python命令行参数解析模块------argparse

      首先,argparse 是python自带的命令行参数解析包,可以用来方便地读取命令行参数,当你的代码需要频繁地修改参数的时候,使用这个工具可以将参数和代码分离开来,让你的代码更简洁,适用范围更广 ...

  5. python argparse type_python argparse(参数解析模块)

    这是一个参数解析,可以用它快捷的为你的程序生成参数相关功能 import argparse(导入程序参数模块) # 创建argparse对象,并将产品简要说明加入 show = '程序说明' ===& ...

  6. argparse模块_Argparse:一个具体案例教会你python命令行参数解析

    问题描述: 现有一个用于数据格式转换的py脚本(多转一),执行时通过命令行传入一系列的参数控制其具体运行方式,使满足以下要求: 1. 必须传入需要处理的原始数据文件名 2. 可以指定输入文件的格式,若 ...

  7. python 命令行参数-Python 命令行参数解析

    Python用于编写脚本的场景非常多,如何处理脚本(命令行)的参数当然非常关键 首先导入sys,参数列表在sys.arg中 import sys if __name__ == '__main__': ...

  8. vsCode运行python设置argparse参数

    想在vsCode中调试带参数的python程序,参数设置方式. Run->open Configurations,打开lanuch.json.在lanuch.json中添加代码后效果如下: &q ...

  9. python 中argparse 实例解析

    一 概念: argparse是python的一个命令行解析包.它可以使写用户友好的命令行接口变得非常容易.该模块定义什么参数是需要的,并且能指出怎么解析sys.argv的参数.它也可以自动的生成帮助和 ...

最新文章

  1. jekyll静态博客提升访问速度:内嵌CSS,异步加载js,压缩HTML
  2. 误差向量幅度(EVM)介绍
  3. 《移动应用开发》作业——JavaScript
  4. 关于Python的执行原理你了解吗?
  5. python3知识点汇总_35个高级Python知识点总结
  6. 【树莓派】最常用的树莓派 Linux 命令及说明
  7. Visual Studio Code 1.48 发布
  8. 远程桌面配置php,Win2008 R2实现多用户远程连接设置方法(图)
  9. 使用dva框架的总结
  10. SQLyog中文版安装教程
  11. 海康威视工业相机SDK的开发使用笔记
  12. 《华为问题管理法》读书笔记2
  13. cpu测试稳定性软件,测试CPU稳定性工具Prime95
  14. mySQL首行缩进快捷键_word段首如何缩进两个字符
  15. WIFI智能插座Homekit
  16. 极光IM系列之java后台集成
  17. linux下boost编译安装全过程脚本塈bzip2编译安装全过程脚本
  18. 暴力破解无线密码最详细教程
  19. 文件上传下载之文件上传
  20. linux 前端开发软件下载,linux前端开发工具下载_系统之家

热门文章

  1. python——循环器(iterator)中count、cycle和repeat函数用法
  2. vivo AI计算平台 Kubernetes集群Ingress网关实践
  3. GAN介绍 - 为什么学习生成式模型?
  4. tcpdump命令详解
  5. 热门iOS与android手机参数
  6. 清华大学录取通知书又火了!各大高校通知书争奇斗艳美到哭!
  7. 一起和B站陈睿,了解各类up主
  8. koala java,GitHub - lijiankun24/Koala: 从 Java 字节码到 ASM 实践
  9. html怎么让表格整体置顶,css如何让表格居中?
  10. java202302java学习笔记第十五天-罗马数字的两种写法2