Python Arguments With Argparse module: The Template I Use for CLI Scripting
Jul 10, 2021
The aim of this playbook🏁 is to try to standardize a simple use of argparse module in Python for passing named arguments from CLI (PowerShell in my case).
steps
- import argparse module
- use if
__name__ == "__main__": main()
pattern to execute from terminal - parse arguments within the
main()
function that has no parameters as all - define an
init_argparse()
function: - create a parser object by calling
argparse.ArgumentParser()
- declare one or more arguments with
parser.add_argument("--<long_param_name>")
- return parser
- parse args by creating an args object by calling
parser.parse_args()
- define a function proper with
param1
,param2
, ... - call function_proper with params being assigned as attributes of an args object. e.g.
function_proper(param1=args.param1, param2=args.param2)
- within a shell call the module with named arguments:
- e.g.
python foobar.py --param1="foo" --param2=="bar"