【问题标题】:How do I import from a subdirectory?如何从子目录导入?
【发布时间】:2014-04-08 04:49:17
【问题描述】:

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

|-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

这不会发生在我的另一台笔记本电脑上,它们的$PYTHONPATHs 是相同的:

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

【问题讨论】:

  • logging != logger...
  • 好像a problem that can no longer be reproduced or a simple typographical error.
  • 对不起 - 这是一个错字。固定的。但问题仍然存在。
  • 如果你在没有测试的情况下执行“import modules.lib.logger”,你会得到同样的错误?

标签: python import path osx-mavericks pythonpath


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多