插件模式 + 子命令 [英] plugins pattern + sub command

查看:21
本文介绍了插件模式 + 子命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将做一个具有插件功能的命令行应用程序,每个新插件将由来自 __main__.py 脚本的子命令调用.

I will do a command line application with plugin capability, each new plugin will be invoked by a sub command from a __main__.py script.

我曾经使用 argparse,我想知道是否可以使用 argparse 来实现子命令 + 插件看起来像(我找到了一些工具,但使用了不推荐使用的包)?

I used to use argparse, I wonder if it's possible with argparse to implement sub command + plugin looking like (I found some tool but using deprecated packages) ?

myfantasticCLI
├── __main__.py
└── plugins
    ├── create.py
    ├── notify.py
    └── test.py

我知道我可以使用 argparse 作为子命令,但不知道如何以动态加载的方式使用它.:/

I know that I could use argparse for sub command, but don't know how to use it in a dynamic loading way. :/

推荐答案

如果你用

sp = parser.add_subparsers(dest='cmd',...)

然后在解析后 args.cmd 将是所选子解析器或命令的名称.

then after parsing args.cmd will be the name of the chosen subparser or command.

然后一个简单的if树可以导入并运行所需的模块

Then a simple if tree could import and run the desired modules

cmd = args.cmd
if cmd in ['module1',...]:
   import plugins.module1 as mod:
   mod.run(...)
elif cmd in ['module2',....]:
   import plugins.module2 as mod:
   ...

有更好的方法可以做到这一点,但我更喜欢从显而易见的开始.

There are fancier ways of doing this, but I prefer starting with the obvious.

此外,我的重点是从解析器中获取 cmd 名称,而不是导入给定名称的模块的详细信息.您不需要 argparse 来测试问题的 import 给定名称 部分.

Also my focus is on getting the cmd name from the parser, not on the details of importing a module given the name. You don't need argparse to test the import given a name part of the problem.

这篇关于插件模式 + 子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆