Python argparse 处理命令行小结
Python argparse 处理命令行小结
1. 关于argparse
是python的一个命令行解析包,主要用于处理命令行参数
2. 基本用法
test.py是测试文件,其内容如下:
import argparse
parser = argparse.ArgumentParser()
parser.parse_args() 测试:
/home $ python test.py
/home $ python test.py --help
usage: test.py [-h]
optional arguments:
-h, --help show this help message and exit /home $ python test.py -v
usage: test.py [-h]
test.py: error: unrecognized arguments: -v /home $ python test.py tt
usage: test.py [-h]
test.py: error: unrecognized arguments: tt
第一个没有任何输出和出错
第二个测试为打印帮助信息,argparse会自动生成帮助文档
第三个测试为未定义的-v参数,会出错
第四个测试为未定义的参数tt,出错
3. positional arguments
修改test.py的内容如下:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo 测试:
/home $ python test.py
usage: test.py [-h] echo
test.py: error: too few arguments /home $ python test.py -h
usage: test.py [-h] echo positional arguments:
echo optional arguments:
-h, --help show this help message and exit /home $ python test.py tt
tt
定义了一个叫echo的参数,默认必选
第一个测试为不带参数,由于echo参数为空,所以报错,并给出用法(usage)和错误信息
第二个测试为打印帮助信息
第三个测试为正常用法,回显了输入字符串tt
4. optional arguments
中文名叫可选参数,有两种方式:
一种是通过一个-来指定的短参数,如-h;
一种是通过--来指定的长参数,如--help
这两种方式可以同存,也可以只存在一个,修改test.py内容如下:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
print "verbosity turned on" 注意这一行:parser.add_argument("-v", "--verbosity", help="increase output verbosity")
定义了可选参数-v或--verbosity,通过解析后,其值保存在args.verbosity变量中
用法如下: /home $ python test.py -v 1
verbosity turned on /home $ python test.py --verbosity 1
verbosity turned on /home $ python test.py -h
usage: test.py [-h] [-v VERBOSITY] optional arguments:
-h, --help show this help message and exit
-v VERBOSITY, --verbosity VERBOSITY
increase output verbosity /home $ python test.py -v
usage: test.py [-h] [-v VERBOSITY]
test.py: error: argument -v/--verbosity: expected one argument
测试1中,通过-v来指定参数值
测试2中,通过--verbosity来指定参数值
测试3中,通过-h来打印帮助信息
测试4中,没有给-v指定参数值,所以会报错
5. action='store_true'
上一个用法中-v必须指定参数值,否则就会报错,有没有像-h那样,不需要指定参数值的呢,答案是有,通过定义参数时指定action="store_true"即可,用法如下
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
print "verbosity turned on" 测试:
/home $ python test.py -v
verbosity turned on /home $ python test.py -h
usage: test.py [-h] [-v] optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
第一个例子中,-v没有指定任何参数也可,其实存的是True和False,如果出现,则其值为True,否则为False
6. 类型 type
默认的参数类型为str,如果要进行数学计算,需要对参数进行解析后进行类型转换,如果不能转换则需要报错,这样比较麻烦
argparse提供了对参数类型的解析,如果类型不符合,则直接报错。如下是对参数进行平方计算的程序:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('x', type=int, help="the base")
args = parser.parse_args()
answer = args.x ** 2
print answer 测试:
/home $ python test.py 2
4
/home $ python test.py two
usage: test.py [-h] x
test.py: error: argument x: invalid int value: 'two' /home $ python test.py -h
usage: test.py [-h] x positional arguments:
x the base optional arguments:
-h, --help show this help message and exit
第一个测试为计算2的平方数,类型为int,正常
第二个测试为一个非int数,报错
第三个为打印帮助信息
7. 可选值choices=[]
5中的action的例子中定义了默认值为True和False的方式,如果要限定某个值的取值范围,比如6中的整形,限定其取值范围为0, 1, 2,该如何进行呢?
修改test.py文件如下:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer 测试:
/home $ python test.py 4 -v 0
16
/home $ python test.py 4 -v 1
4^2 == 16
/home $ python test.py 4 -v 2
the square of 4 equals 16
/home $ python test.py 4 -v 3
usage: test.py [-h] [-v {0,1,2}] square
test.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
/home $ python test.py -h
usage: test.py [-h] [-v {0,1,2}] square positional arguments:
square display a square of a given number optional arguments:
-h, --help show this help message and exit
-v {0,1,2}, --verbosity {0,1,2}
increase output verbosity
测试1, 2, 3 为可选值范围,通过其值,打印不同的格式输出;
测试4的verbosity值不在可选值范围内,打印错误
测试5打印帮助信息
8. 自定义帮助信息help
上面很多例子中都为help赋值,如
parser.add_argument("square", type=int, help="display a square of a given number")
在打印输出时,会有如下内容
positional arguments:
square display a square of a given number
也就是help为什么,打印输出时,就会显示什么
9. 程序用法帮助
8中介绍了为每个参数定义帮助文档,那么给整个程序定义帮助文档该怎么进行呢?
通过argparse.ArgumentParser(description="calculate X to the power of Y")即可
修改test.py内容如下:
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y if args.quiet:
print answer
elif args.verbose:
print "{} to the power {} equals {}".format(args.x, args.y, answer)
else:
print "{}^{} == {}".format(args.x, args.y, answer)
打印帮助信息时即显示calculate X to the power of Y
/home $ python test.py -h
usage: test.py [-h] [-v | -q] x y calculate X to the power of Y positional arguments:
x the base
y the exponent optional arguments:
-h, --help show this help message and exit
-v, --verbose
-q, --quiet
10. 互斥参数
在上个例子中介绍了互斥的参数
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
第一行定义了一个互斥组,第二、三行在互斥组中添加了-v和-q两个参数,用上个例子中的程序进行如下测试: /home $ python test.py 4 2
4^2 == 16
/home $ python test.py 4 2 -v
4 to the power 2 equals 16
/home $ python test.py 4 2 -q
16
/home $ python test.py 4 2 -q -v
可以看出,-q和-v不出现,或仅出现一个都可以,同时出现就会报错。
可定义多个互斥组
11.参数默认值
介绍了这么多,有没有参数默认值该如何定义呢?
修改test.py内容如下:
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], default=1,
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer 测试:
/home $ python test.py 8
8^2 == 64
/home $ python test.py 8 -v 0
64
/home $ python test.py 8 -v 1
8^2 == 64
/home $ python test.py 8 -v 2
the square of 8 equals 64
可以看到如果不指定-v的值,args.verbosity的值默认为1,为了更清楚的看到默认值,也可以直接打印进行测试。
Python argparse 处理命令行小结的更多相关文章
- python argparse:命令行参数解析详解
简介 本文介绍的是argparse模块的基本使用方法,尤其详细介绍add_argument内建方法各个参数的使用及其效果. 本文翻译自argparse的官方说明,并加上一些笔者的理解 import a ...
- 如何让python脚本支持命令行参数--getopt和click模块
一.如何让python脚本支持命令行参数 1.使用click模块 如何使用这个模块,在我前面的博客已经写过了,可参考:https://www.cnblogs.com/Zzbj/p/11309130.h ...
- Noah的学习笔记之Python篇:命令行解析
Noah的学习笔记之Python篇: 1.装饰器 2.函数“可变长参数” 3.命令行解析 注:本文全原创,作者:Noah Zhang (http://www.cnblogs.com/noahzn/) ...
- python生成linux命令行工具
您是否也曾一直想生成类似cd, cat等小巧/迷人/实用的小工具作为系统命令或者将python程序打包为exe进行分发?ok,机会来了.利用python 的argparse 和 pyinstaller ...
- Python解析Linux命令行
写了个python脚本在linux需要传入参数使用,python参数传入有几个方法, 先用了Python中命令行参数的最传统的方法sys.argv linux cmd ~& python ma ...
- 『Argparse』命令行解析
一.基本用法 Python标准库推荐使用的命令行解析模块argparse 还有其他两个模块实现这一功能,getopt(等同于C语言中的getopt())和弃用的optparse.因为argparse是 ...
- [python] 自动生成命令行工具 - fire 简介
转自 Alan Lee Python 中用于生成命令行接口(Command Line Interfaces, CLIs)的工具已经有一些了,例如已经成为 Python 标准库的 argparse 和第 ...
- argparse:命令行参数解析详解
简介# 本文介绍的是argparse模块的基本使用方法,尤其详细介绍add_argument内建方法各个参数的使用及其效果. 本文翻译自argparse的官方说明,并加上一些笔者的理解 Copy im ...
- Python多线程同步命令行模拟进度显示
最近在一个Python(3.5)的小项目中需要用到多线程加快处理速度,同时需要显示进度,于是查了些资料找到几个实现方法:线程池的map-reduce和Queue结合线程的实现.这里简单的实例介绍一下Q ...
随机推荐
- [Leetcode] 5279. Subtract the Product and Sum of Digits of an Integer
class Solution { public int subtractProductAndSum(int n) { int productResult = 1; int sumResult = 0; ...
- 未能加载文件或程序集“Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。系统找不到指定的文件。
网站部署到IIS提示Microsoft.Web.Infrastructure,未能加载 解决方案 使用nuget安装 Microsoft.Web.Infrastructure拷贝到bin目录下面
- Matplotlib 绘图与可视化 一些控件的介绍和属性,反正就是乱七八糟的
这个链接里有下面这个图(图里还有超链接):https://matplotlib.org/3.1.1/api/artist_api.html#matplotlib.artist.Artist 各种图例: ...
- python机器学习---线性回归案例和KNN机器学习案例
散点图和KNN预测 一丶案例引入 # 城市气候与海洋的关系研究 # 导包 import numpy as np import pandas as pd from pandas import Serie ...
- 某安全设备未授权访问+任意文件下载0day
具体是哪家就不说了,硬件盒子,主要检测病毒. payload如下: https://xxx.xxx.xxx.xxx/downTxtFile.php?filename=/etc/passwd 比较简单, ...
- xamarin Mqtt
1 什么是MQTT? mqtt (Message Queuing Telemetry Transport,消息队列遥测传输)是 IBM 开发的一个即时通讯协议,有可能成为物联网的重要组成部分.MQTT ...
- python基础-面向对象编程之组合
面向对象编程之组合 定义:一个对象中拥有另一个或其他多个对象的属性和方法. 作用:减少代码的冗余,降低耦合度 关于耦合度的说明 耦合:通俗地讲,就是相互作用,相互影响的意思 耦合度越高,程序的可扩展性 ...
- 串口 PLC 编程FAQ
1. 不要频繁打开关闭串口,这是个耗时的过程,如果多个工位都争夺串口资源,则会出现卡顿,死锁. 2. PLC 的读写估计100毫秒,如果并发的写,有的写操作会失败,需要Delay或重试. 3. 通常一 ...
- Kotlin开发springboot项目(一)
Kotlin开发springboot项目(一) Kotlin语言与Xtend语言有很多相似之处 为什么会存在这么多JVM语言? 现存的语言提供了太过受限制的功能,要不就是功能太过繁杂,导致语言的臃肿和 ...
- Django框架(七)-- 模板层:模板导入、模板继承、静态文件
一.模板导入 要复用一个组件,可以将该组件写在一个文件中,在使用的时候导入即可 在模板中使用 1.语法 {% include '模板名字' %} 2.使用 ad.html页面 <div clas ...