Python之命令行参数解析
Python 做为一个脚本语言,可以很方便地写各种工具。当你在服务端要运行一个工具或服务时,输入参数似乎是一种硬需(当然你也可以通过配置文件来实现)。
如果要以命令行执行,那你需要解析一个命令行参数解析的模块来帮你做这个苦力活。
Python 本身就提供了三个命令行参数解析模块,我这里罗列一下它们的大致情况供你了解。
getopt
,只能简单的处理命令行参数optparse
,功能强大,易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。argparse
,使其更加容易的编写用户友好的命令行接口。它所需的程序进程了参数定义,argparse将更好的解析sys.argv。同时argparse模块还能自动生成帮助及用户输入错误参数时的提示信息。
很多初学者可能会使用getopt
,上手简单功能也简单。比如说optget
无法解析一个参数多个值的情况,如 --file file1 file2 file3
,而 optparse
实际上我没有用过,但是考虑到它在Python2.7后就已经弃用不再维护,我们通常也不会使用它。
接下来只剩下 argparse
这一神器,它几乎能满足我对命令解析器的所有需求。它支持解析一参数多值,可以自动生成help命令和帮助文档,支持子解析器,支持限制参数取值范围等等功能。
0. HelloWorld
不管学习什么东西,首先第一步都应该是掌握它的大体框架。
而 使用 argparse 前,框架很简单,你只需要记住这三行。
# mytest.py
import argparse
parser = argparse.ArgumentParser(description="used for test")args = parser.parse_args()
现在可以尝试一下
[root@localhost ~]# python mytest.py -h
usage: mytest.py [-h]used for testoptional arguments:-h, --help show this help message and exit
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# python mytest.py
[root@localhost ~]#
已经可以使用了。
1. 入门配置
这里先讲一下,比较常用的参数配置。
- 调试:debug
- 版本号:version
import argparse
parser = argparse.ArgumentParser()parser.add_argument('--version', '-v', action='version',version='%(prog)s version : v 0.01', help='show the version')parser.add_argument('--debug', '-d', action='store_true',help='show the version',default=False)args = parser.parse_args()
print("=== end ===")
上面debug处的配置,需要讲一下的是 action='store_true'
和 default = False
的作用和区别
store_true
:一旦指定了 -d 或者 --debug ,其值就为 True,store_false则相反default=False
:未指定 -d 或者 --debug,其值就默认为False
当我们执行 python mytest.py -v
,就会打印 version 里的内容。
[root@localhost ~]# python mytest.py -v
mytest.py version : v 0.01
[root@localhost ~]#
一旦执行时,指定了参数 -v ,执行到 parser.parse_args() 就会退出程序,不会打印最后的 === end ===
add_argument()常用的参数:
- dest:如果提供dest,例如dest="a",那么可以通过args.a访问该参数
- default:设置参数的默认值
- action:参数触发的动作
- store:保存参数,默认
- store_const:保存一个被定义为参数规格一部分的值(常量),而不是一个来自参数解析而来的值。
- store_ture/store_false:保存相应的布尔值
- append:将值保存在一个列表中。
- append_const:将一个定义在参数规格中的值(常量)保存在一个列表中。
- count:参数出现的次数
- parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity")
- version:打印程序版本信息
- type:把从命令行输入的结果转成设置的类型
- choice:允许的参数值
- parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity")
- help:参数命令的介绍
2. 参数种类
参数可分为 必选参数(positional arguments) 和 可选参数(optional arguments)。
在argsparse 里如何实现呢?
必选参数
用单词做参数,默认就为必选参数
# mytest.py
import argparseparser = argparse.ArgumentParser()
parser.add_argument("name")args = parser.parse_args()print(args.name)
不指定name参数运行一下:python mytest.py
[root@localhost ~]# python mytest.py
usage: mytest.py [-h] name
mytest.py: error: too few arguments
[root@localhost ~]#
如预期一样,报错了,说缺少参数。那我们指定一下:python mytest.py name wangbm
[root@localhost ~]# python mytest.py wangbm
wangbm
[root@localhost ~]#
可选参数
有两种方式:
- 单下划线 - 来指定的短参数,如
-h
; - 双下划线
--
来指定的长参数,如--help
# mytest.py
import argparseparser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="increase output verbosity")args = parser.parse_args()if args.verbosity:print("verbosity turned on")
else:print("verbosity turned off")
试着运行一下 python mytest.py
,不会报错。
[root@localhost ~]# python mytest.py
verbosity turned off
[root@localhost ~]#
3. 参数类型
有的参数,是字符串,有的参数,是数值。
为了对命令行中的参数进行有效的约束,我们可以事先对参数的类型进行声明。argparse 会对参数进行校验,不通过时,会直接抛出错误。
# mytest.py
import argparseparser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("age", type=int)args = parser.parse_args()print(args.name)
print(args.age)
测试一下。
[root@localhost ~]# python mytest.py wangbm eighteen
usage: mytest.py [-h] name age
mytest.py: error: argument age: invalid int value: 'eighteen'
[root@localhost ~]#
[root@localhost ~]# python mytest.py wangbm 18
wangbm
18
[root@localhost ~]#
你看,写 eighteen
就不行,提示类型不合法,只有写 18
才行。
4. 互斥参数
有些参数,是互斥的,有你无我。比如,性别。
在 argparse 中如何实现?
import argparseparser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-m", "--male", action="store_true")
group.add_argument("-f", "--female", action="store_true")
args = parser.parse_args()
如果同时指定了这两个参数,就会报错。
[root@localhost ~]# python mytest.py -f
[root@localhost ~]# python mytest.py -m
[root@localhost ~]# python mytest.py -m -f
usage: mytest.py [-h] [-m | -f]
mytest.py: error: argument -f/--female: not allowed with argument -m/--male
[root@localhost ~]#
5. 可选值
如果是性别,可以像上面那样放在两个参数里然后用互斥组来约束,也可以放在一个参数里,在argparse里限制再在外层做判断。
# mytest.py
import argparseparser = argparse.ArgumentParser()
parser.add_argument("-g", "--gender", default='male',choices=['male', 'female'])args = parser.parse_args()
print(args.gender)
试着执行一下,发现性别只能是男或女,不能为人妖。
[root@localhost ~]# python mytest.py --gender male
male
[root@localhost ~]# python mytest.py --gender female
female
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# python mytest.py --gender other
usage: mytest.py [-h] [-g {male,female}]
mytest.py: error: argument -g/--gender: invalid choice: 'other' (choose from 'male', 'female')
[root@localhost ~]#
6. 指定文件
经常会有那种要在脚本中指定配置文件或者其他文件的需求。可以使用下面的配置
import argparse
parser = argparse.ArgumentParser()parser.add_argument('--file', '-f', action='append',dest='files',help=('additional yaml configuration files to use'),type=argparse.FileType('rb'))args = parser.parse_args()
dest=files
,是说将命令行中,--file
的参数值赋值给变量files,你可以用args.files访问。
action=append
,由于我们会有指定多个文件的需求,那就指定多次--file
,argparse会将其放在一个list里。
type=argparse.FileType('rb')
,既然是指定文件,那么参数应该为路径,并指定打开模式为rb,如果如果要取得文件内容,可以用 args.files[0].read()
7. 子解析器
如果你对命令行,有过足够多的接触,就会知道有些情况下会有子解析器。
这里我以自己工作中,碰到的例子来举个例子。
cloud-init --debug single -name mymodule
其中 single 后面是一个子解析器。
# cloud-init.pydef main_single(name, args):print("name: ", name)print("args: ", args)print("I am main_single")# 添加一个子解析器
subparsers = parser.add_subparsers()parser_single = subparsers.add_parser('single',help='run a single module')# 对single 子解析器添加 action 函数。
parser_single.set_defaults(action=('single', main_single))# require=True,是说如果命令行指定了single解析器,就必须带上 --name 的参数。
parser_single.add_argument("--name", '-n', action="store",help="module name to run",required=True)args = parser.parse_args()(name, functor) = args.action
if name in ["single"]:functor(name, args)
执行命令cloud-init single -name mymodule
,输出如下
name: single
args: Namespace(action=('single', <function main_single at 0x0000000003F161E0>), debug=False, file=None, name='mymodule')
I am main_single
以上就是关于 argparse
工具的使用方法,你学会了吗?
Python之命令行参数解析相关推荐
- Python的命令行参数解析
文章作者:Tyan 博客:noahsnail.com | CSDN | 简书 命令行参数解析在编程语言中基本都会碰到,Python中内置了一个用于命令项选项与参数解析的模块argparse.下 ...
- python argparse命令行参数解析
argparse是python用于解析命令行参数和选项的标准模块. 很多时候,需要用到解析命令行参数的程序,目的是在终端窗口输入训练的参数和选项. argparse 模块可以让人轻松编写用户友好的命令 ...
- windows 下 Python的命令行参数解析 argparse模块 的使用
argparse模块是Python内置的参数解析模块,相较于传统的 sys.argv 来说,其功能更加的强大,操作也更灵活. ArgumentParser类创建时的参数如下: prog - 程 ...
- python带命令行参数解析的文件遍历脚本(找出文件名长度大于某值的文件)
背景 复制一个目录时,提示有个文件名太长未能复制成功,然后忘记是哪个了,现在要靠脚本把它找出来. 代码 #!/usr/bin/pythonimport getopt import os import ...
- python getopt使用_Python命令行参数解析模块getopt使用实例
这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参考下 格式 getopt(args, options ...
- python命令行参数解析OptionParser类用法实例
python命令行参数解析OptionParser类用法实例 本文实例讲述了python命令行参数解析OptionParser类的用法,分享给大家供大家参考. 具体代码如下: from opt ...
- Python命令行参数解析模块------argparse
首先,argparse 是python自带的命令行参数解析包,可以用来方便地读取命令行参数,当你的代码需要频繁地修改参数的时候,使用这个工具可以将参数和代码分离开来,让你的代码更简洁,适用范围更广 ...
- Python中最好用的命令行参数解析工具
Python 做为一个脚本语言,可以很方便地写各种工具.当你在服务端要运行一个工具或服务时,输入参数似乎是一种硬需(当然你也可以通过配置文件来实现). 如果要以命令行执行,那你需要解析一个命令行参数解 ...
- python 命令行参数-Python 中最好用的命令行参数解析工具
Python 做为一个脚本语言,可以很方便地写各种工具.当你在服务端要运行一个工具或服务时,输入参数似乎是一种硬需(当然你也可以通过配置文件来实现). 如果要以命令行执行,那你需要一个命令行参数解析的 ...
最新文章
- 分区表导入导出[未完]
- learnpython_LearnPython_week1
- MySQL FIND_IN_SET(s1,s2)	返回在字符串s2中与s1匹配的字符串的位置
- Linux加载Linux的引导程序,Linux的引导-引导加载程序:LILO和GRUB
- ASP.NET 2.0 中的 DataSource 系列控件
- Nginx 模块的使用
- 超详细图解!【MySQL进阶篇】SQL优化-索引-存储引擎
- 从底层分析c和类c语言
- php 分词技术,php实现的中文分词类完整实例
- 计算机机房建设标准.doc,计算机机房建设规范标准
- 表情键盘 EmojiKeyboard
- 偏最小二乘(Partial Least Squares,PLS)原理及模型建立
- strong标签和b标签,dfn标签,abbr和acronym标签,em和i标签完整介绍
- 一个从业(非正品)奢侈品十年从业者的经验和历程。
- 【学习笔记】数组的地址分配及指针数组的使用
- 输入一行只包含加法和乘法的算式,输出结果
- 【Python相关】PyCharm如何修改行注释颜色
- 【心理咨询师考试笔记】操作技能(三)——咨询基本技能
- 腾讯QQ企业邮箱设置
- 计算机操作校本培训教材,初中教师校本培训教材.doc