繁体   English   中英

如何从子目录导入?

[英]How do I import from a subdirectory?

这是复杂项目中存在的问题的简化。 在一个名为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目录运行它时, 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/:

解决的办法是安装一个名为tester的模块。 即使我显式运行python ~/test/tester.py ,它仍然会运行已安装的模块。 卸下该模块可解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM