How to use one or more same positional arguments in Python?


Introduction..

If we were writing a program that performs arithematic operations on two numbers, we could define them as two positional arguments. But since they are the same kinds/python data types of arguments, it might make more sense to use the nargs option to tell argparse that you want exactly two of same types.

How to do it..

1. Let's write a program to substract two numbers (both the arguments are of same type).

Example

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()
  • The nargs=2 will require exactly two values.

  • Each value must be send as an integer value else our program will error out.

Let us run the program by passing different values.

Output

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

Updated on: 10-Nov-2020

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements