如何从子目录导入?

时间:2014-04-08 04:49:18

标签: python import path osx-mavericks pythonpath

这是复杂项目中存在的问题的简化。 在名为root_test的文件夹中,我有一个名为test的文件夹,其中包含tester.py。我还有(在testmodules目录(空),其中包含lib目录,其中包含logger.py。 Dir结构如下。

|-root_test
|---test/
|-----tester.py
|-----__init__.py
|-----modules/
|-------__init__.py
|-------lib/
|---------__init__.py
|---------logger.py

或者,从root_test

开始
 $ ls
test

 $ ls test/
__init__.py  modules      tester.py

 $ ls test/modules/
__init__.py  lib

 $ ls test/modules/lib/
__init__.py  logger.py

tester.py如下:

#!/usr/bin/env python

import sys, os

# allow running without installing
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))

import test.modules.lib.logger

但是当我尝试从root_test目录运行它时,我收到以下错误:

 $ python test/tester.py 
Traceback (most recent call last):
  File "test/tester.py", line 8, in <module>
    import test.modules.lib.logger
ImportError: cannot import name logger

这不会发生在我的其他笔记本电脑上,而他们的$PYTHONPATH是相同的:

 $ echo $PYTHONPATH
/usr/local/lib/python2.7/dist-packages/:/usr/local/lib/python2.7/site-packages/:

1 个答案:

答案 0 :(得分:0)

解决方案是安装了一个名为tester的模块。即使我明确地运行python ~/test/tester.py,它仍然运行已安装的模块。删除该模块可以解决问题。

相关问题