我想实现一个基于插件的文件上传器,可以将文件上传到不同的服务。它从目录加载所有python模块,然后根据要上传到的服务调用它们。
我有一个简单的BaseHandler,它只是所有插件的抽象基类
import abc
class BaseHandler():
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def start(self,startString):
return
我有一个简单的插件,它继承自BaseHandler
from BaseHandler import BaseHandler
class Cloud(BaseHandler):
def start(self,startString):
return
还有加载插件并调用它们的实际代码
import logging
import os
import sys
from BaseHandler import BaseHandler
all_plugins = {}
def load_plugins():
plugin_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),"Handlers")
plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")]
sys.path.insert(0,plugin_dir)
for plugin in plugin_files:
mod = __import__(plugin)
logging.info('Plugins have been loaded from the directory '+plugin_dir)
for plugin in BaseHandler.__subclasses__():
logging.info('Plugin:'+plugin.__name__)
return BaseHandler.__subclasses__()
logging.basicConfig(level=logging.DEBUG)
loadedPlugins = load_plugins()
for plugin in loadedPlugins:
all_plugins[plugin.__name__]= plugin.__class__
handle = all_plugins[plugin.__name__]()
当我尝试在脚本的最后一行中创建插件的实际对象时
handle = all_plugins[plugin.__name__]()
我收到错误
TypeError: __new__() takes exactly 4 arguments (1 given)
。编辑:添加了完整的追溯
Traceback (most recent call last):
File "C:\TestCopy\Test.py", line 24, in <
module>
handle = all_plugins[plugin.__name__]()
TypeError: __new__() takes exactly 4 arguments (1 given)
最佳答案
您正在注册元类,而不是插件本身。
>>> BaseHandler()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class BaseHandler with abstract methods start
我认为您打算存储插件本身:
all_plugins[plugin.__name__] = plugin
__class__
属性是BaseHandler
类。 plugin
对象是类,而不是实例。