无法导入模块 appengine.ext

2 投票
2 回答
1244 浏览
提问于 2025-04-18 20:42

我在玩ndb的时候遇到了一些问题,当我在Python中导入appengine模块时卡住了。这种情况只发生在我的单元测试中。单元测试的代码放在项目根目录下的test.py文件里。

Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from google.appengine.ext import ndb
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named appengine.ext

以下是我.bash_profile文件中与上述内容相关的部分。

APP_ENGINE_HOME="/Users/xxxxx/google-cloud-sdk/platform/google_appengine/"
export PATH=$PATH:$MYSQL:$M2_HOME/bin:$ANT_HOME/bin:$CATALINA_HOME/bin:$APP_ENGINE_HOME

我在google_appengine里有一个叫Google的目录,里面的结构如下:

.Gooogle
+-- __init__.py
+-- appengine
|   +-- __init__.py
|   +-- ext
    |   +-- ndb
    |   +-- __init__.py

请帮帮我。

2 个回答

0

你问的文件夹名字是google吗?看起来你写的是.Gooogle,对吗?

__init__.py这个文件是解释器在查找PYTHONPATH时用的(PYTHONPATH可以像PATH那样设置为环境变量,或者在代码中用类似其他用户回答中提到的方式来修改),它会尝试找到包含__init__.py的文件夹,并把这些文件夹当作模块。里面有自己__init__.py的子文件夹也会被当作子模块等等……

如果PYTHONPATH里包含了那个有google的文件夹,并且这个文件夹里有__init__.py和像appengine这样的文件夹,那么在你的代码里就可以直接导入它了。你能试着运行下面的代码并把结果发出来吗?这样可以显示你PYTHONPATH里有哪些目录。

import sys
print sys.path
3

在应用引擎外使用这些包最简单的方法就是利用 dev_appserver 来进行设置:

import sys
sys.path.insert(0, '/path/to/google_appengine')
import dev_appserver
dev_appserver.fix_sys_path()

# and then e.g.
from google.appengine.ext import ndb

撰写回答