python argparser的具体使用

yipeiwu_com5年前Python基础

一.正常运行:

咱们随便写个文件:

# 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设计】。

相关文章

python笔记之mean()函数实现求取均值的功能代码

用法:mean(matrix,axis=0)  其中 matrix为一个矩阵,axis为参数 以m * n矩阵举例: axis 不设置值,对 m*n 个数求均值,返回一个实数...

python3.7 利用函数os pandas利用excel对文件名进行归类

python3.7 利用函数os pandas利用excel对文件名进行归类

这里用的python 版本是3.7最新的版本写的。 利用excel ,对门店的二维码对对应所属小区进行分类,比如在excel 江南摩尔店对应浙北大区,那么二维码名字为...

python中的迭代和可迭代对象代码示例

什么是迭代(iteration)呢? 给定一个list或者tuple,通过for循环来遍历这个list或者tuple、这种遍历就是迭代(iteration)。只要是可迭代的对象都可以进行...

通过Py2exe将自己的python程序打包成.exe/.app的方法

通过Py2exe将自己的python程序打包成.exe/.app的方法

Windows 10 x64 macOS Sierra 10.12.4 Python 2.7 准备好装哔~了么,来吧,做个真正意义上的绿色小软件 Win下发布应用 起因 今天实验室同学看...

10种检测Python程序运行时间、CPU和内存占用的方法

10种检测Python程序运行时间、CPU和内存占用的方法

在运行复杂的Python程序时,执行时间会很长,这时也许想提高程序的执行效率。但该怎么做呢? 首先,要有个工具能够检测代码中的瓶颈,例如,找到哪一部分执行时间比较长。接着,就针对这一部分...