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

Updated:   |  Python (Scripting) articles

Command line arguments, options and flags can be created using

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 Buy Me A Coffee



Comments


Add a Comment


Please enter fe0482 in the box below so that we can be sure you are a human.