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

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

问题描述

我将使用具有插件功能的命令行应用程序,每个新的插件将由来自 __ 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 with

sp = 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 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.

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天全站免登陆