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中声明只包含一个元素的元组数据方法
Aug 25 Python
Python中的choice()方法使用详解
May 15 Python
python 3.7.0 安装配置方法图文教程
Aug 27 Python
Django Rest framework解析器和渲染器详解
Jul 25 Python
Django 创建新App及其常用命令的实现方法
Aug 04 Python
django项目中使用手机号登录的实例代码
Aug 15 Python
python中setuptools的作用是什么
Jun 19 Python
如何使用Python处理HDF格式数据及可视化问题
Jun 24 Python
基于Python制作一副扑克牌过程详解
Oct 19 Python
celery在python爬虫中定时操作实例讲解
Nov 27 Python
正确的理解和使用Django信号(Signals)
Apr 14 Python
Python基础学习之奇异的GUI对话框
May 27 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
header跳转和include包含问题详解
2012/09/08 PHP
javascript学习笔记(十八) 获得页面中的元素代码
2012/06/20 Javascript
Three.js源码阅读笔记(基础的核心Core对象)
2012/12/27 Javascript
javascript函数的四种调用模式
2017/01/08 Javascript
操作按钮悬浮固定在微信小程序底部的实现代码
2019/08/02 Javascript
微信小程序点击列表跳转到对应详情页过程解析
2019/09/26 Javascript
微信小程序在text文本实现多种字体样式
2019/11/08 Javascript
使用vuex存储用户信息到localStorage的实例
2019/11/11 Javascript
JavaScript中的this/call/apply/bind的使用及区别
2020/03/06 Javascript
Node.js设置定时任务之node-schedule模块的使用详解
2020/04/28 Javascript
Javascript实现简易天数计算器
2020/05/18 Javascript
Vue实现购物车实例代码两则
2020/05/30 Javascript
[02:08:58]2014 DOTA2国际邀请赛中国区预选赛 Ne VS CIS
2014/05/22 DOTA
[27:53]2014 DOTA2华西杯精英邀请赛 5 24 NewBee VS iG
2014/05/26 DOTA
[02:22:36]《加油!DOTA》总决赛
2014/09/19 DOTA
python实现博客文章爬虫示例
2014/02/26 Python
python爬虫之xpath的基本使用详解
2018/04/18 Python
python中subprocess批量执行linux命令
2018/04/27 Python
Python sorted函数详解(高级篇)
2018/09/18 Python
使用tensorflow实现VGG网络,训练mnist数据集方式
2020/05/26 Python
浅谈tensorflow使用张量时的一些注意点tf.concat,tf.reshape,tf.stack
2020/06/23 Python
Python必须了解的35个关键词
2020/07/16 Python
Python Matplotlib简易教程(小白教程)
2020/07/28 Python
python 实现弹球游戏的示例代码
2020/11/17 Python
Chemist Warehouse官方海外旗舰店:澳洲第一连锁大药房
2017/08/25 全球购物
全球最大的在线旅游公司:Expedia
2017/11/16 全球购物
英国家庭珠宝商:T. H. Baker
2018/02/08 全球购物
美国二手复古奢侈品包包购物网站:LXRandCo
2019/06/18 全球购物
自荐信格式
2013/12/01 职场文书
优秀党员主要事迹
2014/01/19 职场文书
电气工程及其自动化专业求职信
2014/06/23 职场文书
校园文化艺术节宣传标语
2014/10/09 职场文书
预备党员自我批评思想汇报
2014/10/10 职场文书
小学一年级数学教学计划
2015/01/20 职场文书
详解Python函数print用法
2021/06/18 Python
Spring boot实现上传文件到本地服务器
2022/08/14 Java/Android