如何在 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='Numbers of type int for subtraction')

return parser.parse_args()

def main():
args = get_args()
num1, num2 = args.numbers
print(f" *** Subtracting two number - {num1} - {num2} = {num1 - num2}")

if __name__ == '__main__':
main()
  • nargs=2 將需要恰好兩個值。

  • 每個值都必須作為整數傳送,否則我們的程式將出錯。

透過傳遞不同的值來執行程式。

輸出

<<< python test.py 30 10
*** Subtracting two number - 30 - 10 = 40

<<< python test.py 30 10
*** Subtracting two number - 30 - 10 = 20

<<< python test.py 10 30
*** Subtracting two number - 10 - 30 = -20

<<< python test.py 10 10 30
usage: test.py [-h] int int
test.py: error: unrecognized arguments: 30

<<< python test.py
usage: test.py [-h] int int
test.py: error: the following arguments are required: int

更新於:10-11-2020

719 瀏覽次數

開啟你的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.