Python Tips: Parsing arguments for your application
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
Leave Python Tips: Parsing arguments for your application to:
Read more #hive-129924 posts
Best Posts From Agile Automation
We have not curated any of agileautomation's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Agile Automation
- Python Tip for the Week
- Python - Console Improvements - Rich Library
- How Did I Learn Python? What About You?
- F strings in Python - How to use Them?
- Python - Some Things That Make it Unique
- Data Slicing in Python
- Various Ways to Get Data from Python Arrays
- Python Tips: MORE Parsing arguments for your application
- Python Tips: Parsing arguments for your application
- Python Tips: Parsing arguments for your application