我已尝试将以下行添加到我的处理程序脚本 (main.py),但它似乎不起作用:
sys.path.append('subdir')
subdir
位于我的根目录中(即包含 app.yaml
的目录)。
这似乎不起作用,因为当我尝试导入位于 subdir
中的模块时,我的应用程序崩溃了。
最佳答案
1) 确保在 subdir
中有一个空白的 __init__.py
文件。
2) 使用完整路径;像这样:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))
编辑:提供更多信息以回答评论中提出的问题。
As Nick Johnson demonstrates您可以将这三行代码放在名为 fix_path.py
的文件中。然后,在您的 main.py
文件中,在所有其他导入之前执行此 import fix_path
。 Link to a tested application using this technique .
而且,是的,__init__.py
文件是必需的;根据 documentation :
When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.
The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case,__init__.py
can just be an empty file, but it can also execute initialization code for the package or set the__all__
variable, described later.
关于python - 如何修改 Google App Engine (Python) 中的 sys.path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2354166/