Replies: 2 comments 1 reply
-
Here's an example on how I've done it with Click: class PluginCommands(click.MultiCommand):
"""Dynamically read and execute subcommands from specified directory."""
def list_commands(self, ctx):
"""Read subcommand groups from `plugins_dir`."""
rv = []
etl_dir = config.get_value('defaults:directories/etls')
for name in Path(etl_dir).glob('*/*'):
if name.is_file() and name.match('commands.py'):
plugin = name.parent.parts[-1]
rv.append(plugin)
rv.sort()
return rv
def get_command(self, ctx, name):
"""Import and execute subcommand groups from `plugins_dir`."""
try:
mod = importlib.import_module(f"edis.etl.{name}.commands")
# Since `debug` cannot be passed to this function,
# only `print()` can be used. In case of troubleshooting
# uncomment the next line to see if a module is
# imported properly
# print(mod)
except ImportError as e:
raise ImportError(e)
else:
if hasattr(mod, name):
return getattr(mod, name)
else:
return None
@click.command(cls=PluginCommands)
@click.option(
... This reads all files named @click.group()
@click.pass_context
def accounting(ctx, sql_debug):
...
@accounting.command('ilv')
@click.pass_context
def ilv(ctx):
"""Handling of products."""
... But I guess this can be achieved with "Nested Subcommands" in a quite similar way, but not as dynamic as this solution might be. In this case above I do not have to explicitly import any subcommand group, it's auto discovered. Regards, Thomas |
Beta Was this translation helpful? Give feedback.
-
It would be very useful if One possible option might be add support for a string argument to
As opposed to the current:
|
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
I once implemented a solution with Click, which loaded additional commands and their options from other files, i.e. modules. I cannot recall it right now, the code is somewhere on my worker laptop. But speaking generally I have the idea to have main commands in a main file and then run module specific commands.
The sample code may not work right now, but it should demonstrate maybe the main idea. Whenever I run
python main.py run module1
I should be able to add additional options and arguments likemod1_cmd1
. Additionally it should display its own help, likepython main.py run module1 --help
and there I should seemod1_cmd1
andmod1_cmd2
.Has anyone implemented a similar solution with Typer? As I noted above, I have a solution implemented with Click a while ago, so I thought it may be possible with Typer, too, since its core is Click as well.
Regards, Thomas
Operating System
Linux, macOS
Operating System Details
No response
Typer Version
0.7.0
Python Version
3.6.15
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions