From 577ad61cf2b53d09a63b78523d2b94636782ed7e Mon Sep 17 00:00:00 2001 From: Benjamin Sigonneau Date: Sun, 10 Jul 2022 22:21:48 +0200 Subject: [PATCH] Add CLI arguments --- fioul.py | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/fioul.py b/fioul.py index 555eeb1..fcaf382 100644 --- a/fioul.py +++ b/fioul.py @@ -2,9 +2,11 @@ # from bottle import hook, request, route, run, static_file, view +from argparse import ArgumentParser from datetime import date from models import Price, IntegrityError + import requests import json @@ -43,10 +45,46 @@ def store_current_price(): return price -def main(): - print(get_price()) +# ---------------------------------------------------------------------- +# Argument parsing +# use a decorator to simplify argparse usage, as suggested by +# https://mike.depalatis.net/blog/simplifying-argparse.html + +cli = ArgumentParser(description="Balises") +subparsers = cli.add_subparsers(dest="subcommand") + + +def subcommand(args=[], parent=subparsers): + def decorator(func): + parser = parent.add_parser(func.__name__, description=func.__doc__) + for arg in args: + parser.add_argument(*arg[0], **arg[1]) + parser.set_defaults(func=func) + + return decorator + + +@subcommand() +def update(args): store_current_price() +@subcommand() +def show(args): + print(get_price()) + + +# ---------------------------------------------------------------------- +# Main + + +def main(): + args = cli.parse_args() + if args.subcommand is None: + cli.print_help() + else: + args.func(args) + + if __name__ == "__main__": main()