如何在Python中使用一个或多个相同的位置参数?

如何在Python中使用一个或多个相同的位置参数?

更多Python相关文章,请阅读:Python 教程

简介..

如果我们编写一个在两个数字上执行算术运算的程序,我们可以将它们定义为两个位置参数。但是,由于它们是相同种类/Python数据类型的参数,使用nargs选项告诉argparse您需要恰好两个相同类型的参数可能更有意义。

如何做到这一点..

1. 让我们编写一个程序来减去两个数字(两个参数都是同一类型)。

例子

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. nargs - require exactly nargs values.

"""

parser = argparse.ArgumentParser(
description='Example for nargs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('numbers',
metavar='int',
nargs=2,
type=int,
help='数字是 int 类型,用于相减')

return parser.parse_args()

def main():
args = get_args()
num1, num2 = args.numbers
print(f" *** 减去两个数字 - {num1} - {num2} = {num1 - num2}")

if __name__ == '__main__':
main()
  • nargs=2 需要恰好两个值.

  • 每个值必须作为整数值发送,否则我们的程序将出错.

让我们通过传递不同的值来运行程序.

输出

<<< python test.py 30 10
*** 减去两个数字 - 30 - 10 = 40

<<< python test.py 30 10
*** 减去两个数字 - 30 - 10 = 20

<<< python test.py 10 30
*** 减去两个数字 - 10 - 30 = -20

<<< python test.py 10 10 30
usage: test.py [-h] int int
test.py: 错误: 未识别的参数: 30

<<< python test.py
usage: test.py [-h] int int
test.py: 错误: 需要以下参数: int

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程