【问题标题】:Import a python module from a subdirectory of a parent directory从父目录的子目录导入 python 模块
【发布时间】:2015-07-23 23:59:30
【问题描述】:

我有这样的目录结构

dir1/subdir1/module1.py
dir1/subdir2/subdir22/module2.py

假设我将 __init__.py 添加到每个目录和子目录。我想从模块2中导入模块1,在参考了相关问题并尝试了不同的方法后,我找不到解决方案。例如

在模块 2 中我尝试像导入模块 1 一样

from .... import subdir1.module1
from ....subdir1 import module1

上述两个导入都会引发语法错误。

【问题讨论】:

标签: python python-import


【解决方案1】:

这对我有用,

import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.dirname(path.dirname(path.abspath(__file__))) ) ) )

from dir1.subdir1 import module1

【讨论】:

    【解决方案2】:

    以下代码可以从路径加载模块,即使不在包内或不在默认路径上(这里的模块是 Contemplate 我的引擎),但您应该在该文件夹中有一个虚拟的 __init__.py 文件:

    import imp
    ContemplateModulePath = os.path.join(os.path.dirname(__file__), '../src/python/')
    try:
        ContemplateFp, ContemplatePath, ContemplateDesc  = imp.find_module('Contemplate', [ContemplateModulePath])
        Contemplate = getattr( imp.load_module('Contemplate', ContemplateFp, ContemplatePath, ContemplateDesc), 'Contemplate' )
    except ImportError as exc:
        Contemplate = None
        sys.stderr.write("Error: failed to import module ({})".format(exc))
    finally:
        if ContemplateFp: ContemplateFp.close()
    
    if not Contemplate:
        print ('Could not load the Contemplate Engine Module')
        sys.exit(1)
    else:    
        print ('Contemplate Engine Module loaded succesfully')
    

    【讨论】:

      【解决方案3】:

      这对我有用:

      $ mkdir -p dir1/subdir1
      $ mkdir -p dir1/subdir2/subdir22
      $ touch dir1/{,subdir1,subdir2,subdir2/subdir22}/__init__.py
      $ echo 'x = 42' > dir1/subdir1/module1.py
      $ echo 'from ...subdir1.module1 import x; print x' > dir1/subdir2/subdir22/module2.py
      $ python -m dir1.subdir2.subdir22.module2
      42
      

      魔法咒语是

      from ...subdir1.module1 import x
      

      虽然

      from ...subdir1 import module1
      

      也可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-31
        • 2017-10-04
        相关资源
        最近更新 更多