Python命令行参数argv和argparse该如何使用


Posted in Python onFebruary 08, 2021

概述

运行python脚本时通过命令行方式传入运行参数通常有以下两种自建方式:

  • sys.argv - 简洁
  • argparse - 丰富,可自定义

下面详细说一下具体时使用

argv

# test_argv.py

import sys

args = sys.argv
print(f'args = {args}')

>>> output
➜ git:(master) python3 test_argv.py     
args = ['test_argv.py']
➜ git:(master) ✗ python3 test_argv.py 1 2 3
args = ['test_argv.py', '1', '2', '3']
➜ git:(master) ✗ python3 test_argv.py 1 2 3 'hello world !'
args = ['test_argv.py', '1', '2', '3', 'hello world !']

从上面可以看出,通过argv方法获取的结果:

  • 返回为list
  • 第一个参数为脚本本身
  • 如参数中间带空格,用引号即可

argparse

argparse模块的功能较为丰富,其核心是通过add_argument方法自定义入参的:标志、格式、类型和范围等特性,常用如下:

  • *name_or_flag - 定义入参名或flag,如'-n', '--number'
  • type - 指定入参类型
  • choices - 指定入参范围
  • default - 指定入参默认值
  • required - 指定该餐素是否不要,布尔类型
  • help - 参数概述

更多请参考: argparse

实例

test_argv.py

import argparse

# 初始化一个parser对象
parser = argparse.ArgumentParser(description='test module of argparse')

# 指定-n/--number的参数
# 类型为int
# help为简短地说明
parser.add_argument(
  '-n', '--number', type=int,
  help='args of number'
)

# 指定-o/--output参数
# 并限制类型为:['txt', 'csv', 'doc']
parser.add_argument(
  '-o', '--output', type=str,
  choices=['txt', 'csv', 'doc'],
  help='output method'
)

# 指定-d/--default参数
# 并限制类型为:['txt', 'csv', 'doc']
parser.add_argument(
  '-d', '--default', type=int,
  choices=[_ for _ in range(1, 10)],
  default=5,
  help='default'
)

# 指定位置参数foo
parser.add_argument('foo')

args = parser.parse_args()
print(f'args = {args}')

# 获取指定参数
print(
  f'number = {args.number}, type = {type(args.number)}\n'
  f'output = {args.output}, type = {type(args.output)}\n'
  f'default = {args.default}, type = {type(args.default)}\n'
  f'foo = {args.foo}, type = {type(args.foo)}'
)

output

# -h - 打印help
➜ git:(master) ✗ python3 test_argv.py -h
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
          [-d {1,2,3,4,5,6,7,8,9}]
          foo

test module of argparse

positional arguments:
 foo

optional arguments:
 -h, --help      show this help message and exit
 -n NUMBER, --number NUMBER
            args of number
 -o {txt,csv,doc}, --output {txt,csv,doc}
            output method
 -d {1,2,3,4,5,6,7,8,9}, --default {1,2,3,4,5,6,7,8,9}
            default
# 不带参数运行,结果为None
➜ git:(master) ✗ python3 test_argv.py  
args = Namespace(number=None, output=None)
number = None
output = None

# 带参数运行
➜ git:(master) ✗ python3 test_argv.py -n 33 --output txt
args = Namespace(number=33, output='txt')
number = 33, type = <class 'int'>
output = txt, type = <class 'str'>

# 参数格式错误
➜ git:(master) ✗ python3 test_argv.py -n str     
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
test_argv.py: error: argument -n/--number: invalid int value: 'str'
➜ git:(master) ✗ python3 test_argv.py -o excel    
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
test_argv.py: error: argument -o/--output: invalid choice: 'excel' (choose from 'txt', 'csv', 'doc')

# 默认参数 
➜ git:(master) ✗ python3 test_argv.py   
args = Namespace(default=5, number=None, output=None)
number = None, type = <class 'NoneType'>
output = None, type = <class 'NoneType'>
output = 5, type = <class 'int'>

以上就是Python命令行参数argv和argparse该如何使用的详细内容,更多关于Python命令行参数argv和argparse的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python简单的函数定义和用法实例
May 07 Python
21行Python代码实现拼写检查器
Jan 25 Python
python数据结构链表之单向链表(实例讲解)
Jul 25 Python
python中类和实例如何绑定属性与方法示例详解
Aug 18 Python
django限制匿名用户访问及重定向的方法实例
Feb 07 Python
python3安装crypto出错及解决方法
Jul 30 Python
Python使用ffmpy将amr格式的音频转化为mp3格式的例子
Aug 08 Python
python生成器用法实例详解
Nov 22 Python
Python函数默认参数常见问题及解决方案
Mar 26 Python
解决Python中报错TypeError: must be str, not bytes问题
Apr 07 Python
Django如何使用redis作为缓存
May 21 Python
python控制台打印log输出重复的解决方法
May 14 Python
python 实现Requests发送带cookies的请求
Feb 08 #Python
PyCharm2020.3.2安装超详细教程
Feb 08 #Python
python 30行代码实现蚂蚁森林自动偷能量
Feb 08 #Python
如何用Python编写一个电子考勤系统
Feb 08 #Python
python编程的核心知识点总结
Feb 08 #Python
python上下文管理器异常问题解决方法
Feb 07 #Python
python中@contextmanager实例用法
Feb 07 #Python
You might like
Laravel 5使用Laravel Excel实现Excel/CSV文件导入导出的功能详解
2017/10/11 PHP
PHP面向对象程序设计继承用法简单示例
2018/12/28 PHP
Laravel 关联模型-关联新增和关联更新的方法
2019/10/10 PHP
javascript之学会吝啬 精简代码
2010/04/25 Javascript
js全选实现和判断是否有复选框选中的方法
2015/02/17 Javascript
JavaScript实现拖拽网页内元素的方法
2015/04/15 Javascript
js+html5实现canvas绘制简单矩形的方法
2015/06/05 Javascript
javascript简单实现滑动菜单效果的方法
2015/07/27 Javascript
javascript实现支持移动设备画廊
2015/08/24 Javascript
Nodejs实战心得之eventproxy模块控制并发
2015/10/27 NodeJs
纯js实现瀑布流布局及ajax动态新增数据
2016/04/07 Javascript
js简单判断flash是否加载完成的方法
2016/06/21 Javascript
JS控制鼠标拒绝点击某一按钮的实例
2017/12/29 Javascript
Bootstrap fileinput 上传新文件移除时触发服务器同步删除的配置
2018/10/08 Javascript
jQuery实现checkbox全选、反选及删除等操作的方法详解
2019/08/02 jQuery
详解JavaScript自定义函数
2020/07/29 Javascript
python基于multiprocessing的多进程创建方法
2015/06/04 Python
Python装饰器使用实例:验证参数合法性
2015/06/24 Python
Python实现FTP上传文件或文件夹实例(递归)
2017/01/16 Python
非递归的输出1-N的全排列实例(推荐)
2017/04/11 Python
Python查询IP地址归属完整代码
2017/06/21 Python
Python OrderedDict字典排序方法详解
2020/05/21 Python
node中使用shell脚本的方法步骤
2021/03/23 Javascript
控制工程专业个人求职信
2013/09/25 职场文书
运动会稿件200字
2014/02/07 职场文书
品牌推广策划方案
2014/05/28 职场文书
项目经理任命书范本
2014/06/05 职场文书
法学院毕业生求职信
2014/06/25 职场文书
父亲节活动策划方案
2014/08/24 职场文书
孝敬父母的活动方案
2014/08/31 职场文书
酒店办公室主任岗位职责
2015/04/01 职场文书
汽车质检员岗位职责
2015/04/08 职场文书
劳动合同变更协议书范本
2019/04/18 职场文书
Nginx配置之实现多台服务器负载均衡
2021/08/02 Servers
Python+Selenium实现读取网易邮箱验证码
2022/03/13 Python
2022漫威和DC电影上映作品
2022/04/05 欧美动漫