插件模式+子命令 [英] plugins pattern + sub command
问题描述
我将使用具有插件功能的命令行应用程序,每个新的插件将由来自 __ main __。py
脚本的子命令调用。
我曾经使用argparse。我想知道是否可能用argparse实现sud命令+插件看起来像(我发现一些工具,但使用deprecated包)?
myfantasticCLI
├──__main__.py
└──插件
├── create.py
├──notify.py
└──test.py
我知道我可以使用argparse的子命令,但不知道如何使用它与动态加载方式。 :/
如果您使用
argparse >sp = parser.add_subparsers(dest ='cmd',...)
pre>
那么在解析
args.cmd
之后将是所选择的子解析器或命令的名称。
然后,一个简单的
if
树可以导入并运行所需的模块cmd = args.cmd
如果cmd在['module1',...]:
import plugins.module1 as mod:
mod.run (...)
elif cmd in ['module2',....]:
import plugins.module2 as mod:
...
有更好的方法,但我更喜欢从显而易见的开始。
另外我的重点是从解析器获取
cmd
名称,而不是导入给定名称的模块的详细信息。您不需要argparse
来测试导入给定一个名称 c>部分问题。
I will do an command line application with plugin capability, each new plugins will be invoked by a sub command from a
__main__.py
script.I used to use argparse. I wonder if it possible with argparse to implement sud command + plugin looking like (I found some tool but using deprecated packages) ?
myfantasticCLI ├── __main__.py └── plugins ├── create.py ├── notify.py └── test.py
I know that I could use argparse for sub command, but don't know how to use it with a dynamic loading way. :/
解决方案If you initialize the
argparse
subparsers withsp = parser.add_subparsers(dest='cmd',...)
then after parsing
args.cmd
will be the name of the chosen subparser or command.Then a simple
if
tree could import and run the desired modulescmd = 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.
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 needargparse
to test theimport given a name
part of the problem.这篇关于插件模式+子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!