【问题标题】:Importing Python package with custom settings使用自定义设置导入 Python 包
【发布时间】: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 中不起作用。我应该怎么做?

我对@9​​87654334@ 方法也不是很满意。可能它可以做得更好,但我不知道如何。请赐教!

【问题讨论】:

    标签: python python-2.7 python-3.x plugins


    【解决方案1】:

    对于 Python 3,您需要使用相对导入:from .settings import dictionary_path

    否则,它会在您的 sys.path 上的某处寻找 settings

    为了保持一致性,您可以在 Python 2 中使用 from __future__ import absolute_import 获得此行为

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 2021-12-08
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      相关资源
      最近更新 更多