如何在 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.

更新于: 2020-11-10

3K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告