我们如何从文件系统层次结构中主脚本上方的目录导入内容?

时间:2018-04-25 18:34:49

标签: python python-3.x import importerror python-importlib

prj
    -pkg_1
        --file1.py
    -pkg_2
        --file2.py

file2.py内,我们有类似的内容:

# Ye be in dis 'ere file which be name-ed `file2.py`

if __name__ == '__main__':

    ## MAGICAL IMPORT STATEMENT HERE ###
    # import Klass from pkg_1/file1.py
    # definitely do not write `from . [blah, blah, blah]`
    # NO DOTS ALLOWED AFTER `from` inside main script!

else: # We not be da main script

    from ..pkg_1.file1 import Klass

    # go to parent directory of current file
    # (parent dir of `file2.py` is `pkg2`)
    # go to parent_directory_of(`pkg2`) == `proj`
    # look for `pkg_1` under `proj`
    # look for `file1` under `pkg_1`
    # look for `Klass` inside `file1`

我们可以将MAGICAL IMPORT STATEMENT替换为什么?如果我们将file2.py作为主脚本运行,我们就不会"ValueError: attempted relative import beyond top-level package"

0 个答案:

没有答案