如何使用Python中的选项限制参数值?
阅读更多:Python 教程
导言
假设你被要求编写一个程序,用于接受用户输入的网球大满贯冠军数量并对其进行处理。我们已经知道,费德勒和纳达尔在网球中分享了最多的大满贯冠军称号,即20个(截至2020年),而最少为0,许多球员仍在努力争取自己的第一个大满贯冠军。
让我们创建一个接受冠军数量的程序。
注意 - 从终端执行该程序。
示例
import argparse
def get_args():
""" 函数:get_args
.add_argument中使用的参数
1. metavar - 为用户提供数据类型的提示。
- 默认情况下,所有参数都是字符串。
2. type - 实际的Python数据类型
-(请注意,str周围没有引号)
3. help - 对参数的简要描述
"""
parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# 向程序添加第一个参数,类型为int的player titles
parser.add_argument('titles',
metavar='titles',
type=int,
help='GrandSlam Titles')
return parser.parse_args()
# 定义主函数
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():
""" 函数:get_args
.add_argument中使用的参数
1. metavar - 为用户提供数据类型的提示。
- 默认情况下,所有参数都是字符串。
2. type - 实际的Python数据类型
-(请注意,str周围没有引号)
3. help - 对参数的简要描述
4. choices - 用户可以输入的预定义选择范围
"""
parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# 向程序添加第一个参数,类型为int的player titles
parser.add_argument('titles',
metavar='titles',
type=int,
choices=range(0, 20),
help='GrandSlam Titles')
return parser.parse_args()
# 定义主函数
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)
结论:
- 选择选项使用值列表。 如果用户未提供其中之一,则argparse会停止程序。
-
用户必须从数字0-19中选择,否则argparse会出现错误。
最后,您还可以拥有接受字符串选择的程序。
示例
import argparse
def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - 提供关于数据类型的提示。
- 默认情况下,所有参数都是字符串。
2.类型-实际的Python数据类型
-(请注意围绕str的缺乏引号)
3.帮助-对于使用说明书的参数的简要说明
4.choices-用户可以输入此程序的预定义选择范围
"""
parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
#添加我们的第一个参数player names of type str。
parser.add_argument('player', # 球员名称的第一个参数,类型为字符串。
metavar='player',
type=str, # 类型为字符串
choices=['federer', 'nadal', 'djokovic'], #可选的选择项
help='Tennis Players')
# 添加我们的第二个参数player titles of type int
parser.add_argument('titles', # 引号内应为冠军
metavar='titles', # 冠军的第二个参数,类型为整数。
type=int, # 类型为int
choices=range(0, 20), # 竞赛冠军的范围
help='GrandSlam Titles') # 最大胜利
return parser.parse_args()
# 定义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.