Understanding nargs in Python’s argparse

The nargs parameter in Python’s argparse module is a versatile tool that allows developers to specify the number of command-line arguments a program should accept. This feature is essential for creating flexible command-line interfaces that can handle varying numbers of inputs, making it a powerful asset in building user-friendly command-line applications.

Basic Usage of nargs

The nargs option is used to define how many arguments a particular command-line option should consume. It can be set to several different values to control the number of arguments:

  • nargs='*': This setting allows zero or more arguments. It is useful when you want to handle multiple inputs or default to a standard input if no arguments are provided. For example, when reading from multiple files or from STDIN if no files are specified.

    parser.add_argument('file',
                        metavar='FILE',
                        nargs='*',                       # Zero or more of this argument
                        type=argparse.FileType('rt'),    # If arguments are provided, they must be readable text files
                        default=[sys.stdin],             # The default will be a list containing sys.stdin
                        help='Input file(s)')
    
  • nargs='+': This setting requires one or more arguments. It is useful when at least one input is mandatory, such as when summing numbers.

    parser.add_argument('numbers',
                        metavar='int',
                        nargs='+',                                         # One or more values
                        type=int,                                          # All values must be integers
                        help='Numbers')
    

    Example usage:

    $ ./nargs+.py 5
    5 = 5
    $ ./nargs+.py 1 2 3 4
    1 + 2 + 3 + 4 = 10
    
  • nargs='?': This setting allows zero or one argument. It is useful when an argument is optional. For instance, in a word count program, it can be used to optionally accept a file name, defaulting to sys.stdin if no file is specified.

  • nargs=2: This setting requires exactly two arguments. It is useful when a fixed number of inputs is needed, such as when adding two numbers.

    parser.add_argument('numbers',
                        metavar='int',
                        nargs=2,              # Exactly two values
                        type=int,             # Each value must be an integer
                        help='Numbers')
    

Practical Examples

Example 1: Adding Two Numbers

In a program that adds two numbers, you can use nargs=2 to ensure exactly two numbers are provided:

#!/usr/bin/env python3
"""nargs=2"""

import argparse

def get_args():
    """get args"""
    parser = argparse.ArgumentParser(
        description='nargs=2',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('numbers',
                        metavar='int',
                        nargs=2,              # Exactly two values
                        type=int,             # Each value must be an integer
                        help='Numbers')

    return parser.parse_args()

def main():
    """main"""
    args = get_args()
    n1, n2 = args.numbers                     # Two values are expected
    print(f'{n1} + {n2} = {n1 + n2}')         # Numeric addition

if __name__ == '__main__':
    main()

Example 2: Summing Multiple Numbers

To sum an arbitrary number of integers, use nargs='+':

#!/usr/bin/env python3
"""nargs=+"""

import argparse

def get_args():
    """get args"""
    parser = argparse.ArgumentParser(
        description='nargs=+',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('numbers',
                        metavar='int',
                        nargs='+',                                         # One or more values
                        type=int,                                          # All values must be integers
                        help='Numbers')

    return parser.parse_args()

def main():
    """main"""
    args = get_args()
    numbers = args.numbers                                                 # List of numbers
    print('{} = {}'.format(' + '.join(map(str, numbers)), sum(numbers)))   # Sum of numbers

if __name__ == '__main__':
    main()

In this example, args.numbers is always a list, even if only one number is provided.

Conclusion

The nargs parameter in argparse is a versatile tool for handling command-line arguments in Python. By specifying the number of arguments required, developers can create flexible and user-friendly command-line interfaces. Whether you need to handle a fixed number of inputs or a variable list, nargs provides the necessary functionality to accommodate these requirements.

For more detailed examples and explanations, you can refer to the following resources:

Book TitleUsage of nargsTechnical DepthConnections to Other ConceptsExamples UsedPractical Application
Tiny Python Projects: Learn coding and testing with puzzles and gamesDiscusses nargs in the context of creating flexible command-line interfaces, with settings like *, +, ?, and specific numbers. moreProvides detailed explanations of each nargs setting, including how they affect command-line argument parsing. moreConnects nargs to command-line interface design, showing how it can be used to handle multiple inputs or default to standard input. moreIncludes examples like adding two numbers and summing multiple numbers, demonstrating practical use cases. moreEmphasizes creating user-friendly command-line tools that can handle varying numbers of inputs. more
The Quick Python Book, Fourth EditionExplores nargs in the context of command-line utilities, such as a simplified wc utility, using settings like ? and *. moreDiscusses the use of nargs for optional and multiple file inputs, with a focus on practical command-line tool development. moreLinks nargs to file handling and input redirection, showing how it can be used to read from files or standard input. moreProvides a word count program example, illustrating the use of nargs for optional file input. moreFocuses on creating versatile command-line tools that can process multiple files or read from standard input. more

FAQ (Frequently asked questions)

What does ‘nargs’ set to ‘*’ mean in argparse?

What is the default behavior when no file arguments are provided?

What does an asterisk (‘*’) signify when used with 'nargs’?

What does a plus sign (‘+’) signify when used with 'nargs’?

What happens if no file is provided when using ‘nargs’ in the ‘wc’ utility?

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest