如何修改Google App Engine(Python)中的sys.path? [英] How do you modify sys.path in Google App Engine (Python)?

查看:127
本文介绍了如何修改Google App Engine(Python)中的sys.path?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试在我的处理程序脚本(main.py)中添加以下行,但它似乎不起作用:


sys.path.append('subdir')


subdir lives在我的根目录下(即包含 app.yaml 的那个)。



这似乎不起作用,因为当我尝试导入居住在 subdir 中的模块时,我的应用程序爆炸了。

解决方案 1)确保在 subdir 中有一个空的 __ init __。py 文件。

2)使用完整路径;像这样:

  import os 
import sys

sys.path.append( os.path.join(os.path.dirname(__ file__),'subdir'))






编辑:提供更多信息来回答评论中提出的问题。



正如Nick Johnson演示您可以将这三行代码放在名为 fix_path.py 的文件中。然后,在 main.py 文件中,在所有其他导入之前执行 import fix_path 使用此技术链接到经过测试的应用程序



是的, __ init __。py 文件是必需的。根据文档


导入包时,Python
搜索
sys.path中的目录,查找包
子目录。



__ init __。py 文件对于
是必需的,使Python将目录视为包含包的
;这是通过
来防止具有公共
名称的目录(例如
中的字符串)无意中隐藏了稍后在模块搜索
路径中发生的有效模块
。在最简单的情况下,
__ init __。py 可以只是一个空文件,但它也可以执行初始化
代码或设置
__全部__ 变量,稍后介绍。


I've tried adding the following line to my handler script (main.py), but it doesn't seem to work:

sys.path.append('subdir')

subdir lives in the my root directory (i.e. the one containing app.yaml).

This doesn't seem to work, because when I try to import modules that live in subdir, my app explodes.

解决方案

1) Ensure you have a blank __init__.py file in subdir.

2) Use a full path; something like this:

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))


Edit: providing more info to answer questions asked in a comment.

As Nick Johnson demonstrates you can place those three lines of code in a file called fix_path.py. Then, in your main.py file, do this import fix_path before all other imports. Link to a tested application using this technique.

And, yes, the __init__.py file is required; per the 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.

这篇关于如何修改Google App Engine(Python)中的sys.path?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆