Python argparse模块使用方法解析


Posted in Python onFebruary 20, 2020

这篇文章主要介绍了Python argparse模块使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1. 说明

  • argparse 模块是python 用于解析命令行参数和选项的标准模块。
  • 程序定义它需要的参数,然后 argparse 模块将弄清如何从 sys.argv 解析出那些参数。
  • argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。

2. 使用流程

使用argparse 模块配置命令行参数时,需要以下几步:

import argparse

创建 ArgumentParser() 对象

调用 add_argument() 方法添加参数

使用 parse_args() 解析添加的参数, 返回一个命名空间

参数解析完后,进行后续业务逻辑的处理

示例:

import argparse
import json

args_list = ["keywords", "keywords_from_file", "prefix_keywords", "suffix_keywords",
    "limit", "format", "color", "color_type", "usage_rights", "size",
    "exact_size", "aspect_ratio", "type", "time", "time_range", "delay", "url", "single_image",
    "output_directory", "image_directory", "no_directory", "proxy", "similar_images", "specific_site",
    "print_urls", "print_size", "print_paths", "metadata", "extract_metadata", "socket_timeout",
    "thumbnail", "thumbnail_only", "language", "prefix", "chromedriver", "related_images", "safe_search", "no_numbering",
    "offset", "no_download","save_source","silent_mode","ignore_urls"]

def user_input():
 # 创建 ArgumentParser() 对象
 config = argparse.ArgumentParser()
 # 调用 add_argument() 方法添加参数
 config.add_argument('-cf', '--config_file', help='config file name', default='', type=str, required=False)
 config_file_check = config.parse_known_args()
 object_check = vars(config_file_check[0])

 if object_check['config_file'] != '':
  records = []
  json_file = json.load(open(config_file_check[0].config_file))
  for record in range(0,len(json_file['Records'])):
   arguments = {}
   for i in args_list:
    arguments[i] = None
   for key, value in json_file['Records'][record].items():
    arguments[key] = value
   records.append(arguments)
  records_count = len(records)
 else:
  # Taking command line arguments from users
  parser = argparse.ArgumentParser()
  parser.add_argument('-k', '--keywords', help='delimited list input', type=str, required=False)
  parser.add_argument('-kf', '--keywords_from_file', help='extract list of keywords from a text file', type=str, required=False)
  parser.add_argument('-sk', '--suffix_keywords', help='comma separated additional words added after to main keyword', type=str, required=False)
  parser.add_argument('-pk', '--prefix_keywords', help='comma separated additional words added before main keyword', type=str, required=False)
  parser.add_argument('-l', '--limit', help='delimited list input', type=str, required=False)
  parser.add_argument('-f', '--format', help='download images with specific format', type=str, required=False,
       choices=['jpg', 'gif', 'png', 'bmp', 'svg', 'webp', 'ico'])
  parser.add_argument('-u', '--url', help='search with google image URL', type=str, required=False)
  parser.add_argument('-x', '--single_image', help='downloading a single image from URL', type=str, required=False)
  parser.add_argument('-o', '--output_directory', help='download images in a specific main directory', type=str, required=False)
  parser.add_argument('-i', '--image_directory', help='download images in a specific sub-directory', type=str, required=False)
  parser.add_argument('-n', '--no_directory', default=False, help='download images in the main directory but no sub-directory', action="store_true")
  parser.add_argument('-d', '--delay', help='delay in seconds to wait between downloading two images', type=int, required=False)
  parser.add_argument('-co', '--color', help='filter on color', type=str, required=False,
       choices=['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple', 'pink', 'white', 'gray', 'black', 'brown'])
  parser.add_argument('-ct', '--color_type', help='filter on color', type=str, required=False,
       choices=['full-color', 'black-and-white', 'transparent'])
  parser.add_argument('-r', '--usage_rights', help='usage rights', type=str, required=False,
       choices=['labeled-for-reuse-with-modifications','labeled-for-reuse','labeled-for-noncommercial-reuse-with-modification','labeled-for-nocommercial-reuse'])
  parser.add_argument('-s', '--size', help='image size', type=str, required=False,
       choices=['large','medium','icon','>400*300','>640*480','>800*600','>1024*768','>2MP','>4MP','>6MP','>8MP','>10MP','>12MP','>15MP','>20MP','>40MP','>70MP'])
  parser.add_argument('-es', '--exact_size', help='exact image resolution "WIDTH,HEIGHT"', type=str, required=False)
  parser.add_argument('-t', '--type', help='image type', type=str, required=False,
       choices=['face','photo','clipart','line-drawing','animated'])
  parser.add_argument('-w', '--time', help='image age', type=str, required=False,
       choices=['past-24-hours','past-7-days','past-month','past-year'])
  parser.add_argument('-wr', '--time_range', help='time range for the age of the image. should be in the format {"time_min":"MM/DD/YYYY","time_max":"MM/DD/YYYY"}', type=str, required=False)
  parser.add_argument('-a', '--aspect_ratio', help='comma separated additional words added to keywords', type=str, required=False,
       choices=['tall', 'square', 'wide', 'panoramic'])
  parser.add_argument('-si', '--similar_images', help='downloads images very similar to the image URL you provide', type=str, required=False)
  parser.add_argument('-ss', '--specific_site', help='downloads images that are indexed from a specific website', type=str, required=False)
  parser.add_argument('-p', '--print_urls', default=False, help="Print the URLs of the images", action="store_true")
  parser.add_argument('-ps', '--print_size', default=False, help="Print the size of the images on disk", action="store_true")
  parser.add_argument('-pp', '--print_paths', default=False, help="Prints the list of absolute paths of the images",action="store_true")
  parser.add_argument('-m', '--metadata', default=False, help="Print the metadata of the image", action="store_true")
  parser.add_argument('-e', '--extract_metadata', default=False, help="Dumps all the logs into a text file", action="store_true")
  parser.add_argument('-st', '--socket_timeout', default=False, help="Connection timeout waiting for the image to download", type=float)
  parser.add_argument('-th', '--thumbnail', default=False, help="Downloads image thumbnail along with the actual image", action="store_true")
  parser.add_argument('-tho', '--thumbnail_only', default=False, help="Downloads only thumbnail without downloading actual images", action="store_true")
  parser.add_argument('-la', '--language', default=False, help="Defines the language filter. The search results are authomatically returned in that language", type=str, required=False,
       choices=['Arabic','Chinese (Simplified)','Chinese (Traditional)','Czech','Danish','Dutch','English','Estonian','Finnish','French','German','Greek','Hebrew','Hungarian','Icelandic','Italian','Japanese','Korean','Latvian','Lithuanian','Norwegian','Portuguese','Polish','Romanian','Russian','Spanish','Swedish','Turkish'])
  parser.add_argument('-pr', '--prefix', default=False, help="A word that you would want to prefix in front of each image name", type=str, required=False)
  parser.add_argument('-px', '--proxy', help='specify a proxy address and port', type=str, required=False)
  parser.add_argument('-cd', '--chromedriver', help='specify the path to chromedriver executable in your local machine', type=str, required=False)
  parser.add_argument('-ri', '--related_images', default=False, help="Downloads images that are similar to the keyword provided", action="store_true")
  parser.add_argument('-sa', '--safe_search', default=False, help="Turns on the safe search filter while searching for images", action="store_true")
  parser.add_argument('-nn', '--no_numbering', default=False, help="Allows you to exclude the default numbering of images", action="store_true")
  parser.add_argument('-of', '--offset', help="Where to start in the fetched links", type=str, required=False)
  parser.add_argument('-nd', '--no_download', default=False, help="Prints the URLs of the images and/or thumbnails without downloading them", action="store_true")
  parser.add_argument('-iu', '--ignore_urls', default=False, help="delimited list input of image urls/keywords to ignore", type=str)
  parser.add_argument('-sil', '--silent_mode', default=False, help="Remains silent. Does not print notification messages on the terminal", action="store_true")
  parser.add_argument('-is', '--save_source', help="creates a text file containing a list of downloaded images along with source page url", type=str, required=False)
  # 使用 parse_args() 解析添加的参数
  # 默认的 args 的结果:
  # Namespace(aspect_ratio=None, chromedriver=None, color=None, color_type=None, delay=None, exact_size=None, extract_metadata=False, format=None, ignore_urls=False, image_directory=None, keywords=None, keywords_from_file=None, language=False, limit=None, metadata=False, no_directory=False, no_download=False, no_numbering=False, offset=None, output_directory=None, prefix=False, prefix_keywords=None, print_paths=False, print_size=False, print_urls=False, proxy=None, related_images=False, safe_search=False, save_source=None, silent_mode=False, similar_images=None, single_image=None, size=None, socket_timeout=False, specific_site=None, suffix_keywords=None, thumbnail=False, thumbnail_only=False, time=None, time_range=None, type=None, url=None, usage_rights=None)
  args = parser.parse_args() # 返回一个命名空间
  arguments = vars(args) # 返回 args 的属性和属性值的字典
  # arguments 的结构:
  # {'image_directory': None, 'print_urls': False, 'usage_rights': None, 'color': None, 'socket_timeout': False, 'time_range': None, 'chromedriver': None, 'prefix': False, 'extract_metadata': False, 'keywords': None, 'no_numbering': False, 'size': None, 'keywords_from_file': None, 'print_paths': False, 'no_download': False, 'delay': None, 'similar_images': None, 'specific_site': None, 'thumbnail_only': False, 'type': None, 'thumbnail': False, 'metadata': False, 'related_images': False, 'format': None, 'silent_mode': False, 'print_size': False, 'color_type': None, 'exact_size': None, 'no_directory': False, 'suffix_keywords': None, 'single_image': None, 'offset': None, 'output_directory': None, 'language': False, 'url': None, 'prefix_keywords': None, 'save_source': None, 'ignore_urls': False, 'safe_search': False, 'limit': None, 'time': None, 'aspect_ratio': None, 'proxy': None}
  records = []
  records.append(arguments)
 return records

3. 参数说明

add_argument() 函数每个参数解释如下:

  • name or flags - 选项字符串的名字或者列表,例如 foo 或者 -f, --foo。
  • action - 命令行遇到参数时的动作,默认值是 store。
  • store_const,表示赋值为const;
  • append,将遇到的值存储成列表,也就是如果参数重复则会保存多个值;
  • append_const,将参数规范中定义的一个值保存到一个列表;
  • count,存储遇到的次数;此外,也可以继承 argparse.Action 自定义参数解析;
  • nargs - 应该读取的命令行参数个数,可以是具体的数字,或者是?号,当不指定值时对于 Positional argument 使用 default,对于 Optional argument 使用 - - const;或者是 * 号,表示 0 或多个参数;或者是 + 号表示 1 或多个参数。
  • const - action 和 nargs 所需要的常量值。
  • default - 不指定参数时的默认值。
  • type - 命令行参数应该被转换成的类型。
  • choices - 参数可允许的值的一个容器。
  • required - 可选参数是否可以省略 (仅针对可选参数)。
  • help - 参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息.
  • metavar - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称.
  • dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线.

4. 位置参数 设置

以上 描述的是 可选参数的使用,下面描述位置参数的设置,设置了位置参数后,调用脚本时必须要传入对应的值

import argparse
 
parser = argparse.ArgumentParser()
parser.add_argument('a', type=int, help='display an integer param')
args = parser.parse_args()
 
print(args.a)

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

Python 相关文章推荐
python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
Dec 08 Python
Python中常见的数据类型小结
Aug 29 Python
python做量化投资系列之比特币初始配置
Jan 23 Python
Pandas库之DataFrame使用的学习笔记
Jun 21 Python
Python 字符串类型列表转换成真正列表类型过程解析
Aug 26 Python
python实现超市管理系统(后台管理)
Oct 25 Python
python做接口测试的必要性
Nov 20 Python
python 实现在shell窗口中编写print不向屏幕输出
Feb 19 Python
python新手学习使用库
Jun 11 Python
浅谈Keras参数 input_shape、input_dim和input_length用法
Jun 29 Python
Python Merge函数原理及用法解析
Sep 16 Python
请求模块urllib之PYTHON爬虫的基本使用
Apr 08 Python
浅谈pytorch torch.backends.cudnn设置作用
Feb 20 #Python
Python sqlite3查询操作过程解析
Feb 20 #Python
python利用datetime模块计算程序运行时间问题
Feb 20 #Python
pytorch数据预处理错误的解决
Feb 20 #Python
Python异常继承关系和自定义异常实现代码实例
Feb 20 #Python
Python安装与卸载流程详细步骤(图解)
Feb 20 #Python
PyCharm 专业版安装图文教程
Feb 20 #Python
You might like
PHP的面试题集,附我的答案和分析(一)
2006/11/19 PHP
用来解析.htpasswd文件的PHP类
2012/09/05 PHP
Codeigniter中禁止A Database Error Occurred错误提示的方法
2014/06/12 PHP
php保存二进制原始数据为图片的程序代码
2014/10/14 PHP
jQuery 判断元素上是否绑定了事件
2009/10/28 Javascript
通过身份证号得到出生日期和性别的js代码
2009/11/23 Javascript
php 中序列化和json使用介绍
2013/07/08 Javascript
浅析用prototype定义自己的方法
2013/11/14 Javascript
js清理Word格式示例代码
2014/02/13 Javascript
JS基于Mootools实现的个性菜单效果代码
2015/10/21 Javascript
JS简单测试循环运行时间的方法
2016/09/04 Javascript
js实现目录链接,内容跟着目录滚动显示的简单实例
2016/10/15 Javascript
javascript遍历json对象的key和任意js对象属性实例
2017/03/09 Javascript
vue如何引用其他组件(css和js)
2017/04/13 Javascript
在Js页面通过POST传递参数跳转到新页面详解
2017/08/25 Javascript
vue项目国际化vue-i18n的安装使用教程
2018/03/14 Javascript
详解关于JSON.parse()和JSON.stringify()的性能小测试
2019/03/14 Javascript
微信小程序登录数据解密及状态维持实例详解
2019/05/06 Javascript
Ajax获取node服务器数据的完整步骤
2020/09/20 Javascript
Python2.6版本中实现字典推导 PEP 274(Dict Comprehensions)
2015/04/28 Python
Python根据文件名批量转移图片的方法
2018/10/21 Python
Python面向对象之类和实例用法分析
2019/06/08 Python
Python 使用PyQt5 完成选择文件或目录的对话框方法
2019/06/27 Python
Django自定义模板过滤器和标签的实现方法
2019/08/21 Python
python+selenium select下拉选择框定位处理方法
2019/08/24 Python
Dodax奥地利:音乐、电影、书籍、玩具、电子产品等
2019/08/31 全球购物
买卖正宗运动鞋:GOAT
2019/12/06 全球购物
应届毕业生的个人自我鉴定
2013/10/24 职场文书
企业门卫岗位职责
2013/12/12 职场文书
机房搬迁方案
2014/05/01 职场文书
立志成才演讲稿
2014/09/04 职场文书
夫妻忠诚协议范文
2014/11/16 职场文书
军训个人总结
2015/03/03 职场文书
辣妈辣妹观后感
2015/06/10 职场文书
自己搭建resnet18网络并加载torchvision自带权重的操作
2021/05/13 Python
使用pandas或numpy处理数据中的空值(np.isnan()/pd.isnull())
2021/05/14 Python