Python argparse参数别名与简写配置详解

山海之间
山海之间
发布时间:2026-10-13 | 5人浏览过
原创

本文详解Python标准库argparse中配置参数别名与简写的方法。通过add_argument同时指定短选项(如-i)和长选项(如--image),实现用户可任选其一传入参数。同时演示如何为长参数设置多个前缀简写(如--imag, --ima等),提升命令行交互的灵活性与便捷性。

Python argparse参数别名与简写配置详解

一、正常运行情况

基础参数定义与运行示例

首先,我们编写一个基础的测试脚本:


# test.py
import argparse

ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', help='传入图片文件')
args = vars(ap.parse_args())
print(args)

执行该脚本进行测试:


python test.py --image './test.png'
python test.py -i './test.png'

运行结果符合预期:

{'image':'./test.png'}

{'i':'./test.png'}

移除短选项后的行为分析

二、修改程序逻辑


ap.add_argument('--image', help='传入图片文件')

若移除第一个'-i'参数定义,则只能使用长选项:


python test.py --image './test.png'

输出结果如下:

{'image':'./test.png'}

移除长选项后的行为分析

三、进一步调整程序


ap.add_argument('-i', help='传入图片文件')

若移除第一个'--image'参数定义,则只能使用短选项:


python test.py -i './test.png'

输出结果如下:

{'i':'./test.png'}

由此可见,通过同时定义短参和长参,用户可任选其一进行传参。

长参数简写前缀配置技巧

四、传参时的参数简化技巧

在仅传入'--image'参数的情况下:


ap.add_argument('--image', help='传入图片文件')

我们可以灵活使用'--image'、'--imag'、'--ima'、'--im'和'--i'作为参数标识:


python test.py --image './test.png'
python test.py --imag './test.png'
python test.py --ima './test.png'
python test.py --im './test.png'
python test.py --i './test.png'

无论使用哪种形式,输出结果均为:

{'image':'./test.png'}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表