Is it possible to define a hierarchy to python entry points?

Viewed 128

When writing the setup.py file there is an option to add entry points in the following format:

entry_points={
    'console_scripts': [
        'entry_point_name0 = module.file:function0',
        'entry_point_name1 = module.file:function1',
        'entry_point_name2 = module.file:function2'
        ]
    }

However when doing this, even when all three entry points are from the same project they appear as separate commands in the command line. To execute the first entry point I would simply type entry_point_name0 <args> and execute.

Would it be possible to set up a hierarchy to call those commands by first specifying a common name and later the actual entry point name? This would result in calling the first entry point using project_name entry_point_name0 <args>

1 Answers

Yes. Just wrote single entry point that would act as a dispatcher.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('cmd', default='help',
    choices=['help', 'do-good', 'do-evil'],
    help='Command to execute')

args = parser.parse_args()
cmd = args.cmd;

print(f"Your choice is {cmd}")

Works like this:

$ python cmd.py
usage: cmd.py [-h] {help,do-good,do-evil}
cmd.py: error: the following arguments are required: cmd
$ python cmd.py xyz
usage: cmd.py [-h] {help,do-good,do-evil}
cmd.py: error: argument cmd: invalid choice: 'xyz' (choose from 'help', 'do-good', 'do-evil')
$ python cmd.py do-good
Your choice is do-good

You can use argparse's subcommands for this as well: https://docs.python.org/3/library/argparse.html#sub-commands

Related