-
-
Notifications
You must be signed in to change notification settings - Fork 336
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Legacy] 建议在load_plugins中增加对子目录的加载 #3
Comments
对,我当时想要不要支持按目录来分命令集,但是按当时的情况觉得一系列命令放在一个文件就够了,就没,这可能不太好。
上面写完我才发现一个问题, plugin_files = filter(
lambda filename: not filename.startswith('_'),
os.listdir(plugin_dir)
) 这样改动比较少,缺点就是不能放其它类型的文件了(不过一般应该也不会放)。 |
这样不行,我试了下,因为get_plugin_dir中已经指定了plugin_dir_name在get_root_dir下面,因此__init__.py再放__registry__也还是找commands下的py文件,不会去找子目录下的py文件 |
我意思就是让它不光找 py 文件,还找 package(包含
这两个 cmd 应该都可以通过 |
我刚刚测试了一下, def load_plugins(plugin_dir_name, module_callback=None):
plugin_dir = get_plugin_dir(plugin_dir_name)
plugin_files = filter(
lambda filename: not filename.startswith('_'),
os.listdir(plugin_dir)
)
plugins = [os.path.splitext(file)[0] for file in plugin_files]
for mod_name in plugins:
mod = importlib.import_module(plugin_dir_name + '.' + mod_name)
if module_callback:
module_callback(mod) 应该就行了,这样就可以正确导入结构如下的命令:
# commands/cmd1/__init__.py
__registry__ = #... 这样。 |
这段怎么写?我是直接写成__registry__ = cr = CommandRegistry()的,不知道对不对 |
对的吧,还是跟其它模块里的一样, |
我的意思是说不仅仅是导入包的问题,而是你的cmdHub中也有注册指令的问题。
这个还好办,我把__init__.py的代码增加一个init_func就好了
其次,add_registry仍然只是注册了cmd1到registry_map,cmd1/module1并没有注册进去,所以在def call(self, command_name, args_text, ctx_msg, **options)中registry.has(command_name)的判断会导致module1的方法都没法通过,这步还是必须要在add_registry中正确处理遍历package才行 |
不是, 第二点确实是这样,我之前那个改法没有解决子目录中其它模块的导入,但这些模块可以在子目录的 比如使用包的命令可能结构是这样的: # cmd1/__init__.py
__registry__ = cr = CommandRegistry()
from . import module1
from .. import core
@cr.register('hello')
def hello(args_text, ctx_msg):
reply = module1.process(ctx_msg)
core.echo(reply, ctx_msg) # cmd1/module1.py
def process(ctx_msg):
# 一些复杂的逻辑
return '回复' 这时候 我这个思路是目前代码的情况下,快速实现跟以前相同的两级命令划分的(也就是一个子目录(包)就相当于以前的一个模块, |
嗯,原本我也认为不传init_func应该从语句上看没问题,只是跟踪时发现执行到if registry.init_func:的时候就直接跳出了,好像没有执行下面的self.registry_map[registry_name] = registry,不过我也没有深入去找什么原因造成的,如果其他命令没有问题应该是我跟踪时的问题导致的。 所有命令注册放在__init__.py下更不符合我的思路,那就等重构时再讨论这个问题吧,谢谢你的耐心答复,等下我加个你的QQ保持联系。 |
行,我 QQ 1002647525,加的时候备注一下 |
由于一套业务逻辑可能是有几个py组成的,都散落在commands下面对于讲究整洁的我来说是个麻烦事,建议commands中支持子目录,这样也好归集同类业务的指令集。
至于指令的full_command是否要包含子目录可以再考虑一下,我也没想太清楚,包含的话使用时有点繁琐,不包含则可能存在同名的问题。
The text was updated successfully, but these errors were encountered: