How do I use argparse in Python to create an example program?

Published on Aug. 22, 2023, 12:16 p.m.

Here is an example of how to use argparse in Python to create a simple program that takes arguments from the command line:

import argparse

def main(args):
    if args.operation == 'sum':
        result = sum(args.numbers)
    elif args.operation == 'max':
        result = max(args.numbers)
    else:
        raise ValueError('Unsupported operation')

    if args.print_result:
        print(result)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='A program that sums or finds the max of a list of numbers')
    parser.add_argument('operation', choices=['sum', 'max'], help='the operation to perform')
    parser.add_argument('numbers', metavar='N', type=int, nargs='+', help='the list of numbers to operate on')
    parser.add_argument('--print_result', action='store_true', help='print the result')

    args = parser.parse_args()
    main(args)

In this example, we define a main function that takes an args object as an argument. This object is parsed using argparse and contains the operation to perform (sum or max) and the list of numbers to operate on. We then perform the specified operation and optionally print the result.

To run this program, save it to a file (e.g., my_program.py) and run it from the command line with arguments:

python my_program.py sum 1 2 3 4 5 --print_result

This command will calculate the sum of the numbers 1 through 5 and print the result. You can also run the program with max as the operation to calculate the maximum number in the list. The --print_result flag is optional and can be used to control whether or not the result is printed to the console.

Tags:

related content