Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ positional arguments ซ้ำหลายตัวที่มีประเภทเดียวกันใน Python argparse

บทนำ

ถ้าเขียนโปรแกรมคำนวณเลขสองตัว (เช่น ลบ) สามารถกำหนดเป็น positional arguments สองตัว แต่เพราะเป็นประเภทเดียวกัน ใช้ nargs บอก argparse ให้รับค่าสองค่าแบบนี้ดีกว่า

วิธีทำ

  1. เขียนโปรแกรมลบเลขสองตัว (arguments เหมือนกันทั้งคู่)

ตัวอย่าง

import argparse

def get_args():
    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 บังคับให้ต้องป้อนค่าสองค่า ทั้งคู่ต้องเป็น int

ผลลัพธ์

>> 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