แนะนำตัว..
หากเรากำลังเขียนโปรแกรมที่ทำการคำนวณทางคณิตศาสตร์กับตัวเลขสองตัว เราสามารถกำหนดมันเป็นอาร์กิวเมนต์ตำแหน่งสองค่าได้ แต่เนื่องจากเป็นอาร์กิวเมนต์ชนิด/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