1. 程式人生 > 程式設計 >Python argparse模組使用方法解析

Python argparse模組使用方法解析

這篇文章主要介紹了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',required=False)
    parser.add_argument('-kf','--keywords_from_file',help='extract list of keywords from a text file',required=False)
    parser.add_argument('-sk','--suffix_keywords',help='comma separated additional words added after to main keyword',required=False)
    parser.add_argument('-pk','--prefix_keywords',help='comma separated additional words added before main keyword',required=False)
    parser.add_argument('-l','--limit',required=False)
    parser.add_argument('-f','--format',help='download images with specific format',required=False,choices=['jpg','gif','png','bmp','svg','webp','ico'])
    parser.add_argument('-u','--url',help='search with google image URL',required=False)
    parser.add_argument('-x','--single_image',help='downloading a single image from URL',required=False)
    parser.add_argument('-o','--output_directory',help='download images in a specific main directory',required=False)
    parser.add_argument('-i','--image_directory',help='download images in a specific sub-directory',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',choices=['red','orange','yellow','green','teal','blue','purple','pink','white','gray','black','brown'])
    parser.add_argument('-ct','--color_type',choices=['full-color','black-and-white','transparent'])
    parser.add_argument('-r','--usage_rights',help='usage rights',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',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"',required=False)
    parser.add_argument('-t','--type',help='image type',choices=['face','photo','clipart','line-drawing','animated'])
    parser.add_argument('-w','--time',help='image age',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"}',required=False)
    parser.add_argument('-a','--aspect_ratio',help='comma separated additional words added to keywords',choices=['tall','square','wide','panoramic'])
    parser.add_argument('-si','--similar_images',help='downloads images very similar to the image URL you provide',required=False)
    parser.add_argument('-ss','--specific_site',help='downloads images that are indexed from a specific website',required=False)
    parser.add_argument('-p','--print_urls',help="Print the URLs of the images",action="store_true")
    parser.add_argument('-ps','--print_size',help="Print the size of the images on disk",action="store_true")
    parser.add_argument('-pp','--print_paths',help="Prints the list of absolute paths of the images",action="store_true")
    parser.add_argument('-m','--metadata',help="Print the metadata of the image",action="store_true")
    parser.add_argument('-e','--extract_metadata',help="Dumps all the logs into a text file",action="store_true")
    parser.add_argument('-st','--socket_timeout',help="Connection timeout waiting for the image to download",type=float)
    parser.add_argument('-th','--thumbnail',help="Downloads image thumbnail along with the actual image",action="store_true")
    parser.add_argument('-tho','--thumbnail_only',help="Downloads only thumbnail without downloading actual images",action="store_true")
    parser.add_argument('-la','--language',help="Defines the language filter. The search results are authomatically returned in that language",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',help="A word that you would want to prefix in front of each image name",required=False)
    parser.add_argument('-px','--proxy',help='specify a proxy address and port',required=False)
    parser.add_argument('-cd','--chromedriver',help='specify the path to chromedriver executable in your local machine',required=False)
    parser.add_argument('-ri','--related_images',help="Downloads images that are similar to the keyword provided",action="store_true")
    parser.add_argument('-sa','--safe_search',help="Turns on the safe search filter while searching for images",action="store_true")
    parser.add_argument('-nn','--no_numbering',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",required=False)
    parser.add_argument('-nd','--no_download',help="Prints the URLs of the images and/or thumbnails without downloading them",action="store_true")
    parser.add_argument('-iu','--ignore_urls',help="delimited list input of image urls/keywords to ignore",type=str)
    parser.add_argument('-sil','--silent_mode',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",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',help='display an integer param')
args = parser.parse_args()
 
print(args.a)