Python Command Line Arguments Examples

Python has a built-in module called argparse which makes it easy to write user-friendly command-line interfaces. The following are some examples of using argparse to handle command-line arguments:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

This code will define a command-line interface that takes in a list of integers and either calculates the sum or finds the maximum value, depending on the --sum flag. To run this script and sum the values 1 2 3, you would run:

python script.py 1 2 3 --sum

For more information on argparse, see the official Python documentation: https://docs.python.org/3/howto/argparse.html

Leave a Comment