python中的argparse用法

本文介绍Python中的argparse模块,用于创建友好的命令行接口。详解其功能,包括参数解析、自动生成帮助信息及错误处理。并通过实例展示如何使用argparse处理整数输入,计算和或最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python中的argparse用法(实例)

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
argparse是Python中的一个常用模块,和sys.argv()功能类似,主要用于编写命令行接口:对于程序所需要的参数,它可以进行正确的解析。另外,argparse还可以自动的生成help和 usage信息,当程序的参数无效时,它可以自动生成错误信息。

具体实例:
一个可以接受多个整数,并返回它们的和或者最大值的python程序。

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))

具体实例上述程序保存为,prog.py,在终端进入路径下,对程序进行调用,执行并自动提供有用的help信息:python prog.py -h
在这里插入图片描述
对其程序进行有效的输入:

python prog.py 1 2 3 4

在这里插入图片描述

  python prog.py 1 2 3 4 --sum

在这里插入图片描述
If invalid arguments are passed in, it will issue an error:
如果参数传入无效,将会出现错误:

python prog.py a b c

在这里插入图片描述
参考https://docs.python.org/3/library/argparse.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值