Python Tips: Parsing arguments for your application

in #python5 months ago


To parse command-line arguments in Python, you can use the argparse module, which is a powerful tool for writing user-friendly command-line interfaces.

Import in the ArgumentParser and use it to define arguments and parse them.
-dest is the name of the argument to then access in your code
-default allows a default value to be set
-help lets you document the arguement so your python app run with a -h will automatically show the arguments and how to use them

Start with this in your script then run your script with -h option to see the help

from argparse import ArgumentParser

# parse arguments
parser = ArgumentParser()
parser.add_argument("-c", "--config", dest="config_path", default="config", help="set a custom config path", metavar="PATH")
args = parser.parse_args()
print(f"System Arguments: {args}")
print(args.config_path)

If your script in this case is called exampleAPP.py run it with:

python exampleAPP.py -h

and you will get this extra info about your new command line:

usage: exampleAPP.py [-h] [-c PATH]

optional arguments:
  -h, --help            show this help message and exit
  -c PATH, --config PATH
                        set a custom config path

This is a great way to add features to your app and there is so much more you can with arguments, but this should get you started.

Using them in your app then is as simple as refereing the dest name you set:
args.config_path