Files
Obsidian-Main/20.01. Programming/Python/argparse.ArgumentParser.md

2.2 KiB
Raw Permalink Blame History

一個範例:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-u", "--update_tool", default=WIN_FW_UPDATER_PATH, help="The path of win_fw_updater.exe.")
parser.add_argument("-f", "--firmware", required=True, help="The path of ITB file.")
parser.add_argument("-w", "--waittime_update_firmware", default=600, type=int, help="Wait time for update the firmware.")
parser.add_argument("-g", "--ignore_check_file_path", action='store_true', help="Skip check the existence of file.")
args = parser.parse_args()

要求user一定要設定的參數

使用required=True 例如:

parser.add_argument("-f", "--firmware", required=True, help="The path of ITB file.")

如果使用者沒有下-f(或者--firmware=XXX)就會報錯,如下:

FwUpdateCheck.py: error: the following arguments are required: -f/--firmware

有設定才會產生的參數

使用action='store_true'action='store_false' 例如:

parser.add_argument("-g", "--ignore_check_file_path", action='store_true', help="Skip check the existence of file.")

當使用者沒有設置-g時,args.ignore_check_file_pathFalse,當設置時,args.ignore_check_file_pathTrue

使用預設值

例如:

parser.add_argument("-u", "--update_tool", default="C:\\tool.exe", help="The path of win_fw_updater.exe.")

default=<Something>來設定參數的預設值,上面的例子中,args.update_tool的預設值為C:\tool.exe。 另外可以用type=<Object type>來指定預設值的型別。例如:

parser.add_argument("-n", "--number", default=50, type=int, help="Assign a number")

上例中,args.number的預設值是50型別是int,所以可以直接運算,不需要再經過int(args.number)這樣的轉換。

限制使用者的選擇

Example:

parser.add_argument('move', choices=['rock', 'paper', 'scissors'])

使用choices=<list>來限定輸入的選項,上例中,使用者只能輸入'rock'、'paper'、'scissors'這三個字串中的其中一個,否則會報錯:

error: argument move: invalid choice: 'fire' (choose from 'rock', 'paper', 'scissors')