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 | import argparse |
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 | import argparse |
If the required argument is not specified when running the program, an error will be raised:
1 | ➜ python python program.py |
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 | ➜ python python program.py -c blue |
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”]