Python3插件系统
我正在尝试创建一个类似于yapsy的插件框架(不幸的是yapsy与python3不兼容) 我的代码如下所示:Python3插件系统,python,plugin-architecture,Python,Plugin Architecture,我正在尝试创建一个类似于yapsy的插件框架(不幸的是yapsy与python3不兼容) 我的代码如下所示: root main.py plugins/ __init__.py PluginManager.py UI/ __init__.py textui.py 在PluginManager.py中,我定义了以下类: class PluginMetaclass(type): def __i
root
main.py
plugins/
__init__.py
PluginManager.py
UI/
__init__.py
textui.py
在PluginManager.py中,我定义了以下类:
class PluginMetaclass(type):
def __init__(cls, name, base, attrs):
if not hasattr(cls, 'registered'):
cls.registered = []
else:
cls.registered.append((name,cls))
class UI_Plugins(object):
__metaclass__ = PluginMetaclass
#...some code here....
def load():
#...some code here too...
if "__init__" in os.path.basename(candidate_filepath):
sys.path.append(plugin_info['path'])
try:
candidateMainFile = open(candidate_filepath+".py","r")
exec(candidateMainFile,candidate_globals)
except Exception as e:
logging.error("Unable to execute the code in plugin: %s" % candidate_filepath)
logging.error("\t The following problem occured: %s %s " % (os.linesep, e))
if "__init__" in os.path.basename(candidate_filepath):
sys.path.remove(plugin_info['path'])
continue
其中候选文件路径包含插件路径
textui.py包含以下内容:
from root.plugins.PluginManager import UI_Plugins
class TextBackend(UI_Plugins):
def run(self):
print("c")
当我尝试加载插件时,出现以下错误:
No module named plugins.PluginManager
我怎样才能解决这个问题
\uuuu init\uuuuu.py
文件。它可能是空的,但必须在“root”和“plugin”目录中
sys.path
列表中来实现这一点from root.plugins.PluginManager import UI_Plugins
无法工作,因为root
不是包
但是,如果应用程序是以
python3 root/main.py
那么root
实际上不需要是一个包
您只需将textui.py
中的import语句更改为
from plugins.PluginManager import UI_Plugins
每件事都应该正确运作
之所以这样做,是因为当前运行脚本的目录总是自动添加到
sys.path
的开头。在您的情况下,这将是根目录
,由于插件
是该目录中的一个包,因此可以从应用程序中的任何位置直接导入。因此,只要你的main
脚本保持原样,就不需要进行任何其他路径操作。对不起,这当然不是对你问题的直接回答,但是如果你想为python3开发一些非常接近yapsy的东西,那么您可能会对yapsy的新版本感兴趣,我在其中发布了两个与Python 3兼容的软件包:
(参见Yapsy-1.9python3-py3.2.egg或Yapsy-1.9-python3.tar.gz)
位于特定分支上的源代码:
我很抱歉!我犯了个错误!对不起,我更正了原来的帖子。