有一个 ImportError 有可能让我发疯。情况如下所示:
tests/
testWebsite.py
website/
__init__.py
__main__.py
_webtools/
__init__.py
templatedefs.py
...
_templates/
base.mako
article.mako
...
代码(没有测试目录,在问题解决之前我犹豫提交)在这里在线:https ://github.com/Boldewyn/website/ 。
当我调用python -m website.__main__ build
时,主例程使用website/_templates
. 这在任何给定目录中都可以正常工作。
但是,在tests/testWebsite.py
我有一个单元测试中,它也应该运行相同的东西。但是那里的 Mako 模板会引发文件的导入错误,在另一种情况下可以正常导入。
$ head -n 5 website/_templates/article.mako
# -*- coding: utf-8 -*-
<%!
from website._webtools.templatedefs import strip_tags
%>
<%inherit file="base.mako" />
运行测试然后产生:
$ python -m unittest tests.testWebsite
...
ERROR: test_initial_build (tests.testWebsite.BuildTestCase)
Check, if building directly after bootstrap works
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests/testWebsite.py", line 99, in test_initial_build
File "website/_webtools/build.py", line 89, in build
article.save(articles=articles)
File "website/_webtools/articles.py", line 514, in save
template_engine.render_article(self, **ctx)
File "website/_webtools/templates.py", line 52, in render_article
r.render_article(article, **ctx)
File "website/_webtools/templates.py", line 277, in render_article
tpl = self.lookup.get_template(filename)
File "/usr/lib/python2.7/dist-packages/mako/lookup.py", line 217, in get_template
return self._load(srcfile, uri)
File "/usr/lib/python2.7/dist-packages/mako/lookup.py", line 277, in _load
**self.template_args)
File "/usr/lib/python2.7/dist-packages/mako/template.py", line 205, in __init__
module = self._compile_from_file(path, filename)
File "/usr/lib/python2.7/dist-packages/mako/template.py", line 249, in _compile_from_file
filename)
File "/usr/lib/python2.7/dist-packages/mako/template.py", line 470, in _compile_text
exec code in module.__dict__, module.__dict__
File "_templates_article_mako", line 16, in <module>
ImportError: No module named templatedefs
现在,有趣的是,我可以sys.path
直接从模板打印:
<%!
import sys
print sys.path
from website._webtools.templatedefs import strip_tags
%>
我可以在那里确认,那website
是在路上。此外,导入在所有其他部署方案中都运行良好。
导入website
或website._webtools
也很好用。只有website._webtools.templatedefs
部分出错了。
有谁知道,我可以在哪里寻找可能出错的迹象?
测试代码非常简单:
class BuildTestCase(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.cwd = os.getcwd()
os.chdir(self.tmpdir)
bootstrap(self.tmpdir, { # this initiates a new project
"URL": "localhost",
"TITLE": "Example",
"DEFAULTS": {
"AUTHOR": "John Doe",
}
})
def test_initial_build(self):
"""Check, if building directly after bootstrap works"""
build()
def tearDown(self):
os.chdir(self.cwd)
shutil.rmtree(self.tmpdir)
编辑:另一个诊断:我让 mako 编译模板并独立执行生成的 Python 文件。奇迹般有效。我还将 templatedefs.py 减少到最低限度(只有 defs 返回空字符串),这样我也可以在该文件中排除 ImportErrors (或其他怪异)。
系统信息: Ubuntu 11.04、Python 2.7、Mako 0.3.6。