Python 中argparse模块的使用

简介: Python解析命令行读取参数有两种方式:sys.argv和argparse

1 sys.argv


如果脚本很简单或临时使用,没有多个复杂的参数选项,可以直接利用sys.argv将脚本后的参数依次读取(读进来的默认是字符串格式)。

import sys
print("输入的参数为:%s" % sys.argv[1])


命令行执行效果:

>python demo.py 1
输入的参数为:1


2 argparse


如果参数很多,比较复杂,并且类型不统一,那么argparse可以很好的解决这些问题,下面一个实例解释了argparse的基本使用方法

import argparse
# description参数可以用于描述脚本的参数作用,默认为空
parser=argparse.ArgumentParser(description="A description of what the program does")
parser.add_argument('--toy','-t',action='store_true',help='Use only 50K samples of data')
parser.add_argument('--num_epochs',choices=[5,10,20],default=5,type=int,help='Number of epochs.')
parser.add_argument("--num_layers", type=int, required=True, help="Network depth.")
args=parser.parse_args()
print(args)
print(args.toy,args.num_epochs,args.num_layers)


命令行执行效果:

>python demo.py --num_epochs 10 --num_layers 10
Namespace(num_epochs=10, num_layers=10, toy=False)
False 10 10


2.1 基本使用

parser.add_argument('--toy','-t',action='store_true',help='Use only 50K samples of data')


--toy:为参数名称

-t:为参数别称

action='store_true':参数是否使用,如果使用则为True,否则为False

>python demo.py -t --num_epochs 10 --num_layers 10
Namespace(num_epochs=10, num_layers=10, toy=True)
True 10 10 # 对比和上次执行的区别


help:参数说明


2.2 相关参数


  • 实例1

parser.add_argument('--num_epochs',choices=[5,10,20],default=5,type=int,help='Number of epochs.')


choices:候选值,输出参数必须在候选值里面,否如会出现下面的结果:

>python demo.py -t --num_epochs 30 --num_layers 10
usage: demo.py [-h] [--toy] [--num_epochs {5,10,20}] --num_layers NUM_LAYERS
demo.py: error: argument --num_epochs: invalid choice: 30 (choose from 5, 10, 20)


default:默认值,如果不输入参数,则使用该默认值

>python demo.py -t  --num_layers 10
Namespace(num_epochs=5, num_layers=10, toy=True)
True 5 10


int:参数类型

  • 实例2

parser.add_argument("--num_layers", type=int, required=True, help="Network depth.")


required:为必选参数,如果不输入,则出现以下错误:

>python demo.py -t --num_epochs 10
usage: demo.py [-h] [--toy] [--num_epochs {5,10,20}] --num_layers NUM_LAYERS
demo.py: error: the following arguments are required: --num_layers


  • 实例3
    -h:输出参数使用说明信息

>python demo.py -h
usage: demo.py [-h] [--toy] [--num_epochs {5,10,20}] --num_layers NUM_LAYERS
A description of what the program does
optional arguments:
  -h, --help            show this help message and exit
  --toy, -t             Use only 50K samples of data
  --num_epochs {5,10,20}
                        Number of epochs.
  --num_layers NUM_LAYERS
                        Network depth.


相关文章
|
3月前
|
开发者 Python
如何在Python中管理模块和包的依赖关系?
在实际开发中,通常会结合多种方法来管理模块和包的依赖关系,以确保项目的顺利进行和可维护性。同时,要及时更新和解决依赖冲突等问题,以保证代码的稳定性和可靠性
155 62
|
2月前
|
Python
Python Internet 模块
Python Internet 模块。
131 74
|
3月前
|
算法 数据安全/隐私保护 开发者
马特赛特旋转算法:Python的随机模块背后的力量
马特赛特旋转算法是Python `random`模块的核心,由松本真和西村拓士于1997年提出。它基于线性反馈移位寄存器,具有超长周期和高维均匀性,适用于模拟、密码学等领域。Python中通过设置种子值初始化状态数组,经状态更新和输出提取生成随机数,代码简单高效。
141 63
|
3月前
|
数据可视化 Python
如何在Python中解决模块和包的依赖冲突?
解决模块和包的依赖冲突需要综合运用多种方法,并且需要团队成员的共同努力和协作。通过合理的管理和解决冲突,可以提高项目的稳定性和可扩展性
|
3月前
|
Python
Python的模块和包
总之,模块和包是 Python 编程中非常重要的概念,掌握它们可以帮助我们更好地组织和管理代码,提高开发效率和代码质量
133 61
|
3月前
|
测试技术 Python
手动解决Python模块和包依赖冲突的具体步骤是什么?
需要注意的是,手动解决依赖冲突可能需要一定的时间和经验,并且需要谨慎操作,避免引入新的问题。在实际操作中,还可以结合使用其他方法,如虚拟环境等,来更好地管理和解决依赖冲突😉。
|
3月前
|
持续交付 Python
如何在Python中自动解决模块和包的依赖冲突?
完全自动解决所有依赖冲突可能并不总是可行,特别是在复杂的项目中。有时候仍然需要人工干预和判断。自动解决的方法主要是提供辅助和便捷,但不能完全替代人工的分析和决策😉。
|
1月前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
32 3
|
3月前
|
JSON Linux 数据格式
Python模块:从入门到精通,只需一篇文章!
Python中的模块是将相关代码组织在一起的单元,便于重用和维护。模块可以是Python文件或C/C++扩展,Python标准库中包含大量模块,如os、sys、time等,用于执行各种任务。定义模块只需创建.py文件并编写代码,导入模块使用import语句。此外,Python还支持自定义模块和包,以及虚拟环境来管理项目依赖。
Python模块:从入门到精通,只需一篇文章!
|
3月前
|
Python
在Python中,可以使用内置的`re`模块来处理正则表达式
在Python中,可以使用内置的`re`模块来处理正则表达式
89 5

热门文章

最新文章