Python (Scripting) - Command line options flags arguments using argparse

by
Jeremy Canfield |
Updated: March 23 2024
| Python (Scripting) articles
Command line arguments, options and flags can be created using
- sys.argv (older)
- argparse (newer) (this article)
You can:
- Pass in options (also known as key value pairs)
- Pass in flags (True boolean)
Here is a basic example that will create command line options and flags.
- action="store" is used to create an option (key value pair)
- action="store_true" is used to create a flag that contains a value of True (boolean)
#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--environment", action="store", required=False, default="lab", choices=['lab', 'development', 'staging', 'production'])
parser.add_argument("-v", "--validate", action="store_true", required=False, help="run this script in validation mode")
args = parser.parse_args()
if args.validate:
print(f"args.validate = {args.validate}")
print(f"args.environment = {args.environment}")
Did you find this article helpful?
If so, consider buying me a coffee over at