如何在 Python 中使用選擇選項限制引數值?
簡介..
假設你被要求編寫一個程式,從使用者那裡接受網球大滿貫賽冠軍的數量並進行處理。我們已經知道,費德勒和納達爾分享著網球界最多的 20 個大滿貫賽冠軍(截至 2020 年),而最少是 0,許多球員仍在努力爭取他們的第一個大滿貫賽冠軍。
讓我們建立一個程式來接受冠軍數量。
注意 - 從終端執行程式。
示例
import argparse
def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.
2. type - The actual Python data type
- (note the lack of quotes around str)
3. help - A brief description of the parameter for the usage
"""
parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Adding our first argument player titles of type int
parser.add_argument('titles',
metavar='titles',
type=int,
help='GrandSlam Titles')
return parser.parse_args()
# define main
def main(titles):
print(f" *** Player had won {titles} GrandSlam titles.")
if __name__ == '__main__':
args = get_args()
main(args.titles)輸出
我們的程式現在已準備好接受冠軍數量。因此,讓我們將任何數字(而不是浮點數)作為引數傳遞。
<<< python test.py 20 *** Player had won 20 GrandSlam titles. <<< python test.py 50 *** Player had won 50 GrandSlam titles. <<< python test.py -1 *** Player had won -1 GrandSlam titles. <<< python test.py 30 *** Player had won 30 GrandSlam titles.
雖然程式碼在技術上沒有問題,但肯定存在功能性問題,因為我們的程式接受任意數量的大滿貫賽冠軍,包括負數冠軍。
在這種情況下,如果我們想要限制大滿貫賽冠軍的選擇,可以使用 choices 選項。
在下面的示例中,我們將冠軍數量限制在 (0, 20) 的範圍內。
示例
import argparse
def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.
2. type - The actual Python data type
- (note the lack of quotes around str)
3. help - A brief description of the parameter for the usage
4. choices - pre defined range of choices a user can enter to this program
"""
parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Adding our first argument player titles of type int
parser.add_argument('titles',
metavar='titles',
type=int,
choices=range(0, 20),
help='GrandSlam Titles')
return parser.parse_args()
# define main
def main(titles):
print(f" *** Player had won {titles} GrandSlam titles.")
if __name__ == '__main__':
args = get_args()
main(args.titles)輸出
>>> python test.py 30 usage: test.py [-h] titles test.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) <<< python test.py 10 *** Player had won 10 GrandSlam titles. <<< python test.py -1 usage: test.py [-h] titles test.py: error: argument titles: invalid choice: -1 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) <<< python test.py 0 *** Player had won 0 GrandSlam titles. <<< python test.py 20 usage: test.py [-h] titles test.py: error: argument titles: invalid choice: 20 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
結論
choices 選項接受一個值列表。如果使用者未能提供其中一個值,argparse 將停止程式。
使用者必須從 0 到 19 的數字中選擇,否則 argparse 將停止並報錯。
最後,你也可以建立一個接受字串選擇的程式。
示例
import argparse
def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.
2. type - The actual Python data type
- (note the lack of quotes around str)
3. help - A brief description of the parameter for the usage
4. choices - pre defined range of choices a user can enter to this program
"""
parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Adding our first argument player names of type str.
parser.add_argument('player',
metavar='player',
type=str,
choices=['federer', 'nadal', 'djokovic'],
help='Tennis Players')
# Adding our second argument player titles of type int
parser.add_argument('titles',
metavar='titles',
type=int,
choices=range(0, 20),
help='GrandSlam Titles')
return parser.parse_args()
# define main
def main(player,titles):
print(f" *** {player} had won {titles} GrandSlam titles.")
if __name__ == '__main__':
args = get_args()
main(args.player,args.titles)輸出
<<< python test.py usage: test.py [-h] player titles test.py: error: the following arguments are required: player, titles <<< python test.py "federer" 30 usage: test.py [-h] player titles test.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) <<< python test.py "murray" 5 usage: test.py [-h] player titles test.py: error: argument player: invalid choice: 'murray' (choose from 'federer', 'nadal', 'djokovic') <<< python test.py "djokovic" 17 *** djokovic had won 17 GrandSlam titles.
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP