代码之家  ›  专栏  ›  技术社区  ›  Jono

如何从子目录导入?

  •  1
  • Jono  · 技术社区  · 11 年前

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

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

    或者,从 根测试(_T) :

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

    测试程序.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
    

    但当我试着从 根测试(_T) dir,我得到以下错误:

     $ 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 s相同:

     $ echo $PYTHONPATH
    /usr/local/lib/python2.7/dist-packages/:/usr/local/lib/python2.7/site-packages/:
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   Jono    11 年前

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