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 相关文章推荐
pycharm 使用心得(八)如何调用另一文件中的函数
Jun 06 Python
python开发之文件操作用法实例
Nov 13 Python
基于Python如何使用AIML搭建聊天机器人
Jan 27 Python
Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例
Nov 23 Python
Python基于回溯法解决01背包问题实例
Dec 06 Python
Python解析Excle文件中的数据方法
Oct 23 Python
在Python中调用Ping命令,批量IP的方法
Jan 26 Python
Python爬虫抓取技术的一些经验
Jul 12 Python
python实现图像拼接功能
Mar 23 Python
django创建超级用户时指定添加其它字段方式
May 14 Python
Python监听剪切板实现方法代码实例
Nov 11 Python
python基础之类属性和实例属性
Oct 24 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
Ajax PHP 边学边练 之三 数据库
2009/11/26 PHP
PHP利用str_replace防注入的方法
2013/11/10 PHP
PHP实现ASCII码与字符串相互转换的方法
2017/04/29 PHP
redis+php实现微博(一)注册与登录功能详解
2019/09/23 PHP
js常用函数 不错
2006/09/08 Javascript
表单填写时用回车代替TAB的实现方法
2007/10/09 Javascript
js查找某元素中的所有图片地址的方法
2014/01/16 Javascript
js replace(a,b)之替换字符串中所有指定字符的方法
2016/08/17 Javascript
js读取json文件片段中的数据实例
2017/03/09 Javascript
初学者AngularJS的环境搭建过程
2017/10/27 Javascript
RequireJS用法简单示例
2018/08/20 Javascript
详解Webstorm 下的Angular2.0开发之路(图文)
2018/12/06 Javascript
vue使用@scroll监听滚动事件时,@scroll无效问题的解决方法详解
2019/10/15 Javascript
小程序中设置缓存过期的实现方法
2020/01/14 Javascript
[57:59]完美世界DOTA2联赛循环赛 Ink Ice vs LBZS BO2第一场 11.05
2020/11/05 DOTA
Python字符串的encode与decode研究心得乱码问题解决方法
2009/03/23 Python
Python程序设计入门(2)变量类型简介
2014/06/16 Python
python数组过滤实现方法
2015/07/27 Python
Python对数据进行插值和下采样的方法
2018/07/03 Python
python 定义n个变量方法 (变量声明自动化)
2018/11/10 Python
使用python爬取微博数据打造一颗“心”
2019/06/28 Python
详解CSS3+JS完美实现放大镜模式
2020/12/03 HTML / CSS
HTML5打开本地app应用的方法
2016/03/31 HTML / CSS
空字符串(“”)和null的区别
2012/11/13 面试题
2019年c语言经典面试题目
2016/08/17 面试题
企业办公室岗位职责
2014/03/12 职场文书
法人委托书范本
2014/04/04 职场文书
竞选劳动委员演讲稿
2014/04/28 职场文书
经贸日语专业个人求职信范文
2014/04/29 职场文书
室内趣味活动方案
2014/08/24 职场文书
卫校毕业生自我鉴定
2014/09/28 职场文书
2014年小学班主任工作总结
2014/11/08 职场文书
毕业设计致谢语
2015/05/14 职场文书
2019西餐厅创业计划书范文!
2019/07/12 职场文书
Golang ort 中的sortInts 方法
2022/04/24 Golang
MySQL中LAG()函数和LEAD()函数的使用
2022/08/14 MySQL