2009-06-17 55 views
0

我正在爲python中的內部基於xml的元數據格式編寫解析器。我需要提供不同的類來處理不同的標籤。將需要一個相當大的處理程序集合,所以我將它想象成一個簡單的插件系統。我想要做的只是加載包中的每個類,並將其註冊到我的解析器。 我現在的嘗試是這樣的:
(處理程序是包含處理器的包裝,每個處理器有一個靜態成員變量,這是一個字符串數組)簡單的python插件系統

class MetadataParser: 
    def __init__(self): 
     #... 
     self.handlers={} 
     self.currentHandler=None 
     for handler in dir(Handlers): # Make a list of all symbols exported by Handlers 
      if handler[-7:] == 'Handler': # and for each of those ending in "Handler" 
       handlerMod=my_import('MetadataLoader.Handlers.' + handler) 
       self.registerHandler(handlerMod, handlerMod.tags) # register them for their tags 

    # ... 

    def registerHandler(self, handler, tags): 
     """ Register a handler class for each xml tag in a given list of tags """ 
     if not isSequenceType(tags): 
      tags=(tags,) # Sanity check, make sure the tag-list is indeed a list 
     for tag in tags: 
      self.handlers[tag]=handler 

但是,這是行不通的。我收到錯誤AttributeError: 'module' object has no attribute 'tags' 我在做什麼錯?

+1

修復您的縮進。 – SilentGhost 2009-06-17 11:59:45

+1

你並沒有提供太多的信息。錯誤信息可能會說*錯誤發生在哪一行,這顯然有助於查明問題。此外,你的代碼有語法錯誤(在類名稱縮進後缺少冒號),所以你在這裏發佈的內容根本不會運行。此外,錯誤可能發生在您未發佈的代碼的某些部分中...... – sth 2009-06-17 12:13:00

回答

0

首先,道歉爲格式不正確/不正確的代碼。
也感謝您的關注。然而,罪魁禍首就是經常在椅子和鍵盤之間。我通過擁有同名的類和模塊來困惑自己。 my_import的結果(我現在意識到我甚至沒有提及它來自哪裏......它來自SO:link)是一個名爲areaHandler的模塊。我想要這個班,也叫做areaHandler。所以我只需要通過eval('Handlers。'+ handler +'。'+ handler)挑選出類。
再次,感謝您的時間,並且對帶寬

0

可能是您的handlerMod模塊中的一個不包含任何tags變量。

0

我建議您閱讀this page的示例和解釋,其中介紹瞭如何編寫插件體系結構。

0

通過extend_me庫簡單和完全地擴展實現抱歉。

代碼可能看起來像

from extend_me import ExtensibleByHash 

# create meta class 
tagMeta = ExtensibleByHash._('Tag', hashattr='name') 

# create base class for all tags 
class BaseTag(object): 
    __metaclass__ = tagMeta 

    def __init__(self, tag): 
     self.tag = tag 

    def process(self, *args, **kwargs): 
     raise NotImeplemntedError() 

# create classes for all required tags 
class BodyTag(BaseTag): 
    class Meta: 
     name = 'body' 

    def process(self, *args, **kwargs): 
     pass # do processing 

class HeadTag(BaseTag): 
    class Meta: 
     name = 'head' 

    def process(self, *args, **kwargs): 
     pass # do some processing here 

# implement other tags in this way 
# ... 

# process tags 
def process_tags(tags): 
    res_tags = [] 
    for tag in tags: 
     cls = tagMeta.get_class(tag) # get correct class for each tag 
     res_tags.append(cls(tag)) # and add its instance to result 
    return res_tags 

欲瞭解更多信息,看看documentationcode。 此庫用於OpenERP/Odoo RPC lib