Arguments to any application exposes feature optionality to the execution mode of the application. Argument parsing is not something that is touched often. Developers implement the structure once and often make minor edits.
Before we go on, let’s start with the needs of the audience in this article.
User / Audience Narrative
- As a Python software developer, I want to quickly copy and paste code snippets that I can use to add user friendly CLI argument parsing feature in my Python app.
- As a Python software developer, I want to learn about the various uses of “argparse” in Python
Quick Snippets for Copy + Paste
# tested on Python 3.9.10
import argparse
import datetime
def parse_arguments() -> argparse.Namespace:
arg_parser = argparse.ArgumentParser()
# use an integer as the argument value
#
arg_parser.add_argument(
"-a",
"--atasks",
help = "specify the number of async tasks",
type = int,
default = 3,
)
# limit the argument values to a specific set
# in this case 3 modes are provided
#
arg_parser.add_argument(
"-m",
"--mode",
choices = ["mode1", "mode2", "mode3"],
help = "specify the runmode",
type = str,
default = "mode1",
)
# use an integer and constraint the values to a range
# of values
#
arg_parser.add_argument(
"-t",
"--throttlewait",
help = "specify the number of seconds to wait for throttling",
type = int,
choices = range(2, 10), # you know how to use 'range', right? ;)
default = 5,
)
# this is an example of using other libraries to
# generate a default value
#
arg_parser.add_argument(
"-d",
"--date",
help = "specify the date in YYYY-MM-DD format",
type = str,
default = datetime.date.today().strftime("%Y-%m-%d"),
)
return arg_parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
print(args.atasks, type(args.atasks))
print(args.mode, type(args.mode))
print(args.throttlewait, type(args.throttlewait))
print(args.date, type(args.date))
"""
# Above will print:
3 <class 'int'>
mode1 <class 'str'>
5 <class 'int'>
2023-03-05 <class 'str'>
# With the "-h" option we get, presuming the script name is 'i.py':
usage: i.py [-h] [-a ATASKS] [-m {mode1,mode2,mode3}] [-t {2,3,4,5,6,7,8,9}] [-d DATE]
optional arguments:
-h, --help show this help message and exit
-a ATASKS, --atasks ATASKS
specify the number of async tasks
-m {mode1,mode2,mode3}, --mode {mode1,mode2,mode3}
specify the runmode
-t {2,3,4,5,6,7,8,9}, --throttlewait {2,3,4,5,6,7,8,9}
specify the number of seconds to wait for throttling
-d DATE, --date DATE specify the date in YYYY-MM-DD format
"""