/

Accepting Command Line Arguments in Python

Accepting Command Line Arguments in Python

When running a Python program from the command line, you have the ability to pass additional arguments and options. This can be done by using the sys module from the standard library. However, handling arguments this way requires manual validation and error handling. A better alternative is to use the argparse package, which is specifically designed for this purpose.

To begin, import the argparse module and create an instance of ArgumentParser, providing a description of your program:

1
2
3
4
5
import argparse

parser = argparse.ArgumentParser(
description='This program prints the name of my dogs'
)

Next, you can add the arguments you want to accept. For example, in the following program, we accept a -c option to pass a color:

1
2
3
4
5
6
7
8
9
10
11
import argparse

parser = argparse.ArgumentParser(
description='This program prints a color HEX value'
)

parser.add_argument('-c', '--color', metavar='color', required=True, help='the color to search for')

args = parser.parse_args()

print(args.color) # 'red'

If the required argument is not specified when running the program, an error will be raised:

1
2
3
➜ python python program.py
usage: program.py [-h] -c color
program.py: error: the following arguments are required: -c

You can also set an option to only accept specific values using the choices parameter:

1
parser.add_argument('-c', '--color', metavar='color', required=True, choices={'red', 'yellow'}, help='the color to search for')
1
2
3
➜ python python program.py -c blue
usage: program.py [-h] -c color
program.py: error: argument -c/--color: invalid choice: 'blue' (choose from 'yellow', 'red')

These are just the basics of using argparse for handling command line arguments in Python. However, there are additional options and packages available that offer more advanced functionality. Some popular ones include Click and Python Prompt Toolkit, which have gained popularity among the Python community.

tags: [“Python”, “command line arguments”, “argparse”]