最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python argparse模塊使用方法解析

 更新時間:2020年02月20日 11:03:49   作者:酸果實愛吐泡泡的魚  
這篇文章主要介紹了Python argparse模塊使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

這篇文章主要介紹了Python argparse模塊使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

1. 說明

  • argparse 模塊是python 用于解析命令行參數(shù)和選項的標準模塊。
  • 程序定義它需要的參數(shù),然后 argparse 模塊將弄清如何從 sys.argv 解析出那些參數(shù)。
  • argparse 模塊還會自動生成幫助和使用手冊,并在用戶給程序傳入無效參數(shù)時報出錯誤信息。

2. 使用流程

使用argparse 模塊配置命令行參數(shù)時,需要以下幾步:

import argparse

創(chuàng)建 ArgumentParser() 對象

調用 add_argument() 方法添加參數(shù)

使用 parse_args() 解析添加的參數(shù), 返回一個命名空間

參數(shù)解析完后,進行后續(xù)業(yè)務邏輯的處理

示例:

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():
 # 創(chuàng)建 ArgumentParser() 對象
 config = argparse.ArgumentParser()
 # 調用 add_argument() 方法添加參數(shù)
 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() 解析添加的參數(shù)
  # 默認的 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. 參數(shù)說明

add_argument() 函數(shù)每個參數(shù)解釋如下:

  • name or flags - 選項字符串的名字或者列表,例如 foo 或者 -f, --foo。
  • action - 命令行遇到參數(shù)時的動作,默認值是 store。
  • store_const,表示賦值為const;
  • append,將遇到的值存儲成列表,也就是如果參數(shù)重復則會保存多個值;
  • append_const,將參數(shù)規(guī)范中定義的一個值保存到一個列表;
  • count,存儲遇到的次數(shù);此外,也可以繼承 argparse.Action 自定義參數(shù)解析;
  • nargs - 應該讀取的命令行參數(shù)個數(shù),可以是具體的數(shù)字,或者是?號,當不指定值時對于 Positional argument 使用 default,對于 Optional argument 使用 - - const;或者是 * 號,表示 0 或多個參數(shù);或者是 + 號表示 1 或多個參數(shù)。
  • const - action 和 nargs 所需要的常量值。
  • default - 不指定參數(shù)時的默認值。
  • type - 命令行參數(shù)應該被轉換成的類型。
  • choices - 參數(shù)可允許的值的一個容器。
  • required - 可選參數(shù)是否可以省略 (僅針對可選參數(shù))。
  • help - 參數(shù)的幫助信息,當指定為 argparse.SUPPRESS 時表示不顯示該參數(shù)的幫助信息.
  • metavar - 在 usage 說明中的參數(shù)名稱,對于必選參數(shù)默認就是參數(shù)名稱,對于可選參數(shù)默認是全大寫的參數(shù)名稱.
  • dest - 解析后的參數(shù)名稱,默認情況下,對于可選參數(shù)選取最長的名稱,中劃線轉換為下劃線.

4. 位置參數(shù) 設置

以上 描述的是 可選參數(shù)的使用,下面描述位置參數(shù)的設置,設置了位置參數(shù)后,調用腳本時必須要傳入對應的值

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Python MySQL數(shù)據(jù)庫基本操作及項目示例詳解

    Python MySQL數(shù)據(jù)庫基本操作及項目示例詳解

    這篇文章主要介紹了Python連接MySQL數(shù)據(jù)庫后的一些基本操作,并以銀行管理系統(tǒng)項目為例,為大家具體介紹了一下部分功能的實現(xiàn),文中的示例代碼具有一定的學習價值,感興趣的可以了解一下
    2021-12-12
  • 使用Python對微信好友進行數(shù)據(jù)分析

    使用Python對微信好友進行數(shù)據(jù)分析

    這篇文章主要介紹了使用Python對微信好友進行數(shù)據(jù)分析的實現(xiàn)代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-06-06
  • Python3實現(xiàn)的簡單驗證碼識別功能示例

    Python3實現(xiàn)的簡單驗證碼識別功能示例

    這篇文章主要介紹了Python3實現(xiàn)的簡單驗證碼識別功能,涉及Python針對驗證碼圖片識別處理相關操作技巧,需要的朋友可以參考下
    2018-05-05
  • python使用Psutil模塊實現(xiàn)獲取計算機相關信息

    python使用Psutil模塊實現(xiàn)獲取計算機相關信息

    psutil 是一個跨平臺的庫,用于獲取進程和系統(tǒng)運行狀態(tài)的信息,這篇文章主要為大家詳細介紹了python如何調用psutil模塊實現(xiàn)獲取計算機相關信息,有需要的小伙伴可以了解下
    2023-11-11
  • Python爬蟲信息輸入及頁面的切換方法

    Python爬蟲信息輸入及頁面的切換方法

    今天小編就為大家分享一篇Python爬蟲信息輸入及頁面的切換方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • 進一步探究Python中的正則表達式

    進一步探究Python中的正則表達式

    這篇文章主要介紹了Python中的正則表達式的一些用法,正則表達式的使用是Python學習進階中的重要知識,需要的朋友可以參考下
    2015-04-04
  • 基于Python把網(wǎng)站域名解析成ip地址

    基于Python把網(wǎng)站域名解析成ip地址

    這篇文章主要介紹了基于Python把網(wǎng)站域名解析成ip地址,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-05-05
  • Python安裝Talib庫的詳細圖文教程

    Python安裝Talib庫的詳細圖文教程

    talib庫的安裝之路坑特別多,這是最常見的,下面這篇文章主要給大家介紹了關于Python安裝Talib庫的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-12-12
  • Python模塊的定義,模塊的導入,__name__用法實例分析

    Python模塊的定義,模塊的導入,__name__用法實例分析

    這篇文章主要介紹了Python模塊的定義,模塊的導入,__name__用法,結合實例形式分析了Python的概念、功能、導入及__name__相關使用技巧,需要的朋友可以參考下
    2020-01-01
  • Python應用案例之利用opencv實現(xiàn)圖像匹配

    Python應用案例之利用opencv實現(xiàn)圖像匹配

    OpenCV 是一個的跨平臺計算機視覺庫,可以運行在 Linux、Windows 和 Mac OS 操作系統(tǒng)上,這篇文章主要給大家介紹了關于Python應用案例之利用opencv實現(xiàn)圖像匹配的相關資料,需要的朋友可以參考下
    2024-08-08

最新評論

确山县| 吉首市| 宁晋县| 友谊县| 盈江县| 乐业县| 古田县| 金昌市| 临桂县| 弋阳县| 嫩江县| 洛川县| 长岭县| 乐陵市| 玉龙| 怀远县| 射阳县| 衡南县| 隆化县| 宁强县| 红安县| 台北县| 杨浦区| 昌邑市| 勐海县| 秦皇岛市| 兴城市| 高邑县| 化德县| 台湾省| 岫岩| 洮南市| 湾仔区| 长子县| 榆林市| 迭部县| 阳江市| 田阳县| 萍乡市| 拉萨市| 尚志市|