Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use one or more same positional arguments in Python?
Python's argparse module allows you to handle multiple positional arguments of the same type using the nargs parameter. This is particularly useful when you need exactly N arguments of the same data type, like performing arithmetic operations on numbers.
Using nargs for Same Type Arguments
The nargs parameter specifies how many command-line arguments should be consumed. When you set nargs=2, argparse expects exactly two values of the specified type.
Example: Subtracting Two Numbers
Let's create a program that subtracts two integers using positional arguments ?
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
2. type - The actual Python data type
3. help - A brief description of the parameter for 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 numbers - {num1} - {num2} = {num1 - num2}")
if __name__ == '__main__':
main()
Key Points
The
nargs=2requires exactly two valuesEach value must be an integer, otherwise the program will error out
The arguments are automatically parsed into a list and can be unpacked
Output
Running the program with different arguments produces the following results ?
$ python test.py 30 10 *** Subtracting two numbers - 30 - 10 = 20 $ python test.py 10 30 *** Subtracting two numbers - 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: numbers
Other nargs Options
Besides specifying an exact number, nargs supports other useful options ?
import argparse
# nargs='*' - zero or more arguments
parser = argparse.ArgumentParser()
parser.add_argument('numbers', nargs='*', type=int)
args = parser.parse_args(['1', '2', '3'])
print(f"Zero or more: {args.numbers}")
# nargs='+' - one or more arguments
parser2 = argparse.ArgumentParser()
parser2.add_argument('numbers', nargs='+', type=int)
args2 = parser2.parse_args(['5', '10'])
print(f"One or more: {args2.numbers}")
Zero or more: [1, 2, 3] One or more: [5, 10]
Conclusion
Using nargs with argparse makes it easy to handle multiple positional arguments of the same type. Set nargs=N for exactly N arguments, nargs='*' for zero or more, or nargs='+' for one or more arguments.
