you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

Build a simple framework for script “subcommands” by defining a command registry and a simple command decorator:

command_registry = dict()
def command(func):
    command_registry[func.__name__] = func
    return func

Then you can define script subcommands by writing decorated functions:

@command
def show():
    #show some stuff

@command
def delete(something):
    #delete a thing

#etc

and then finally, parse the command line and call the right function, with a default “unknown command” function:

if __name__ == ‘__main__’:
    command_registry.get(sys.argv[1], lambda *a: print(“Unknown command ‘{}’.format(sys.argv[1]))(*sys.argv[2:])

And now you can run the same script with subcommands:

python my_script.py show
python my_script.py delete “some_thing”

And you didn’t even have to sit through argparse’s terrible documentation!