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 against that database 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
The use is quite straight forward. With the code above in a Python script called dump_query.py
and given a series of named queries in an associated file I can do
$ python dump_query.py extract 122 lines written to database $ python dump_query.py query invoices_this_month 38 lines written to invoices_this_month.csv $ python dump_query.py query payee_invoices 'Grace Brothers' 44 lines written to payee_invoices.csv