Python中相对导入的包不在路径上

如何将
python包(不在路径中)的父目录中的文件导入子目录中的文件?

我不完全清楚python包装的词汇,所以举个例子:

dir1/
    __init__.py
    runner.py
    in_dir1.py
    dir2/
        __init__.py
        in_dir2.py

DIR1 / in_dir1.py:

def example():
    print "Hello from dir1/in_dir1.example()"

DIR1 / DIR2 / in_dir2.py

import in_dir1   #or whatever this should be to make this work
print "Inside in_dir2.py, calling in_dir1.example()"
print in_dir1.example()

鉴于dir1不在python路径上,我正在寻找将in_dir1导入in_dir2的最佳方法.

我尝试从.. import in_dir1和..dir1 import in_dir1 based on this Q/A但是都不起作用.执行该意图的正确方法是什么? This Q/A似乎包含答案;但是,我不太清楚如何制作它/如何使用PEP 366实际解决我的问题

两个__init__.py文件都是空的,我在v2.6上.

我试图在不使用谷歌不断出现的任何路径黑客的情况下这样做.

最佳答案 答案在您提供的链接中:

Relative imports use a module’s __name__ attribute to determine that
module’s position in the package hierarchy. If the module’s name does
not contain any package information (e.g. it is set to ‘main‘)
then relative imports are resolved as if the module were a top level
module, regardless of where the module is actually located on the file
system.

你不能在__main__脚本中进行相对导入(即如果你直接运行python in_dir2.py).

要解决这个问题,PEP 366允许你做的是设置全局__package__:

import dir1
if __name__ == '__main__':
    __package__ = 'dir1.dir2'
    from .. import in_dir1

请注意,包dir1仍然必须在sys.path上!您可以操作sys.path来实现此目的.但到那时,你在绝对进口方面取得了哪些成就?

点赞