TIL - Python ArgParse Run One Function
I’m building a command line executable in Python. It’s going to be a single script that has multiple functions, one to extract some data to a SQLite database, and another to run a query using aiosql.
The pattern I want to follow here is that the first argument to the script describes the operation to carry out and then following that are arguments to that operation.
I’ve implemented this pattern in Python using the
argparse library as follows;
import argparse parser = argparse.Argument_Parser("run a single function") parser.add_argument("operation", choices=["extract", "query"], help="The operation to run") parser.add_argument("params", nargs="*", help="Arguments to send to the operation") args = parser.parse_args() if args.operation == "extract": # extract data and put it in our database run_extract() elif args.operation == "query": # run the named query with provided parameters run_query(args.params)
With inspiration from this StackExchange post - https://stackoverflow.com/questions/59314792/how-to-run-different-python-functions-from-command-line