Skip to content

Instantly share code, notes, and snippets.

@fabiomontefuscolo
Last active January 3, 2024 23:12
Show Gist options
  • Save fabiomontefuscolo/b719984c302db33a11be5e3c549af7cd to your computer and use it in GitHub Desktop.
Save fabiomontefuscolo/b719984c302db33a11be5e3c549af7cd to your computer and use it in GitHub Desktop.
import glob
import importlib
from os.path import basename, dirname, join
import click
#
# I have a module called `project.commands`. From time to time I create
# new click commands in a new submodule inside the module mentioned
# above. The idea here is to automagically load all the new commands
# added to `project.commands` submodules.
#
# project/
# commands/
# __init__.py
# dumpdb.py
# importdb.py
# shell.py
# reset_password.py
#
# Then you should be able to
# $ python manage.py dumpdb --other-flags
# $ python manage.py importdb --more-flags
# $ python manage.py shell
# $ python manage.py reset_password --user_id=1 --password "${PASSWORD}"
#
def load_commands() -> click.core.Command:
from project import commands
namespaces = [
f"{commands.__package__}.{basename(file).rstrip('.py')}"
for file in glob.glob(join(dirname(commands.__file__), "*.py"))
if not file.endswith("__init__.py")
]
comms = []
for namespace in namespaces:
module = importlib.import_module(namespace)
comms.extend(
[
comm
for comm in module.__dict__.values()
if isinstance(comm, click.core.Command)
]
)
return comms
@click.group()
def cli():
pass
if __name__ == "__main__":
for command in load_commands():
cli.add_command(command)
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment