【发布时间】:2014-08-15 06:51:17
【问题描述】:
我正在开发一个简单的字典工具,它有一个基类,可以通过插件扩展以表示不同的字典。插件在文件系统中的组织方式如下:
plugins/ ├── dict1 │ ├── ... │ ├── settings.py │ └── dict1.py └── dict2 ├── ... ├── settings.py └── dict2.py
主应用程序像这样发现并加载插件:
import os
PLUGINS_DIR = 'plugins'
PLUGINS_PATH = os.path.join(os.path.dirname(__file__), PLUGINS_DIR)
def discover_dictionaries():
for plugin_name in os.listdir(PLUGINS_PATH):
plugin_path = os.path.join(PLUGINS_PATH, plugin_name, plugin_name + '.py')
if os.path.isfile(plugin_path):
name = '.'.join([PLUGINS_DIR, plugin_name, plugin_name])
module = __import__(name, fromlist=['Dictionary'])
yield plugin_name, getattr(module, 'Dictionary')()
如上文件系统布局所示,大多数插件在同一目录中都有一个settings.py 文件,其中包含插件的自定义设置。插件的主包导入设置如下:
from settings import dictionary_path
这在 Python 2.7 中运行良好。但在 Python 3 中,我得到了这个堆栈跟踪:
Error: could not import Dictionary from /tmp/webdict/plugins/wud/wud.py
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 1, in <listcomp>
File "/tmp/webdict/util.py", line 14, in discover_dictionaries
module = __import__(name, fromlist=['Dictionary'])
File "/tmp/webdict/plugins/wud/wud.py", line 4, in <module>
from settings import dictionary_path
ImportError: No module named 'settings'
settings.py 文件在 /tmp/webdict/plugins/wud/settings.py 中,该程序在 Python 2 上运行良好,但在 Python 3 上运行良好。在运行 Python 3 之前,我用以下命令擦除了所有 *.pyc 文件:
find plugins -name '*.pyc' -delete
完整的项目在GitHub上开源。
重现问题:
# clone test1 branch
git clone -b test1 https://github.com/janosgyerik/webdict
# raises ImportError -> what I want to fix
python3.4 -c 'import util; print([x for x in util.discover_dictionaries()])'
# NO ImportError -> GOOD (the IOError doesn't matter for this test)
python2.6 -c 'import util; print([x for x in util.discover_dictionaries()])'
换句话说,在 Python 2 中,插件对 from settings import blah 没有问题,在自己的目录中有 settings.py,但这在 Python 3 中不起作用。我应该怎么做?
我对@987654334@ 方法也不是很满意。可能它可以做得更好,但我不知道如何。请赐教!
【问题讨论】:
标签: python python-2.7 python-3.x plugins