python argparser的具体使用

yipeiwu_com6年前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判断ip是否可达的实例详解

python中使用subprocess来使用shell 关于threading的用法 from __future__ import print_function import sub...

Python实现简易端口扫描器代码实例

Python实现简易端口扫描器代码实例

在网上的一些资料的基础上自己又添了些新内容,算是Python socket编程练手吧。 #coding=utf-8 import socket import time import...

python anaconda 安装 环境变量 升级 以及特殊库安装的方法

Anaconda 是一个旗舰版的python安装包, 因为普通的python没有库, 如果需要安装一些重要的库, 要经常一个一个下载,会非常麻烦. 所以这个一个集成的, 可以手动批量升级...

在Python上基于Markov链生成伪随机文本的教程

 首先看一下来自Wolfram的定义     马尔可夫链是随机变量{X_t}的集合(t贯穿0,1,...),给定当前的状态,未来与过去条件独立。...

Python中使用第三方库xlrd来读取Excel示例

本篇文章介绍如何使用xlrd来读取Excel表格中的内容,xlrd是第三方库,所以在使用前我们需要安装xlrd。另外我们一般会使用xlwt来写Excel,所以下一篇文章我们会来介绍如何使...