1

我想实现一个基于插件的文件上传器,它可以将文件上传到不同的服务。它从一个目录加载所有 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)
4

1 回答 1

1

您正在注册元类,而不是插件本身;

>>> 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对象是类,而不是实例。

于 2013-02-18T10:27:15.597 回答