python - 如何修改 Google App Engine (Python) 中的 sys.path?

标签 python google-app-engine sys.path

我已尝试将以下行添加到我的处理程序脚本 (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_pathLink 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/

相关文章:

python - 在 Spacy NER 模型中的评估

python - 使用 "current-directory"imports 导入模块

python - 如何使用 sqlalchemy 关系实现多个连接

python - 为笔记本设置默认的 sys.path

Python:选择多个已安装模块版本之一

python - 如何继承 array.array 并让它的派生构造函数在 python 中不带参数?

python - 如何在 App Engine 网站后台持续运行脚本?

android - Cloud Endpoints 在 Android/iOS 客户端库中生成实体 key

python - 如何在appengine python中查询没有祖先的实体

java - 在 Jython 中设置导入模块路径 - 奇怪的行为