包中的Python相对导入不在路径上 [英] Python relative imports within a package not on the path

查看:90
本文介绍了包中的Python相对导入不在路径上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I import a file that is in a parent directory within a python package (that is not on the path) into a file in a child dir?

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

I'm not totally clear on the vocabulary of python packaging so by way of example:

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

dir1/in_dir1.py:

dir1/in_dir1.py:

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

dir1/dir2/in_dir2.py

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的最佳方法.

Given that dir1 is not on the python path I'm looking for the best way to import in_dir1 into in_dir2.

我根据此问答尝试了from .. import in_dir1from ..dir1 import in_dir1 ,但都没有作品.执行该意图的正确方法是什么? 此问题似乎包含了答案;但是,我不太确定该怎么做/如何使用 PEP 366

I tried from .. import in_dir1 and from ..dir1 import in_dir1 based on this Q/A but neither works. What is the correct way of executing that intent? This Q/A seems to contain the answer; however, I'm not quite sure what to make of it / how to actually solve my problem using PEP 366

两个__init__.py文件都是空的,我使用的是 v2.6 .

Both __init__.py files are empty and I am on v2.6.

我正尝试在不使用Google不断出现的任何路径黑客的情况下执行此操作.

I'm attempting to do this without using any of the path hacks that Google keeps turning up.

推荐答案

答案在您提供的链接中:

The answer is in the link you gave:

相对导入使用模块的__name__属性来确定 模块在包层次结构中的位置.如果模块名称正确 不包含任何程序包信息(例如,将其设置为"主要") 然后解析相对导入,就好像该模块是顶级模块一样 模块,无论模块实际位于文件中的何处 系统.

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).

You cannot do relative imports in __main__ scripts (i.e. if you directly run python in_dir2.py).

要解决此问题,PEP 366允许您执行的操作是设置全局__package__:

To solve this, what PEP 366 allows you to do is set the global __package__:

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

请注意,软件包dir1仍必须位于sys.path上!您可以操纵sys.path来实现这一点.但是到那时,您在绝对进口方面取得了什么成就?

Note that the package dir1 still has to be on sys.path! You can manipulate sys.path to achieve this. But by then, what have you achieved over absolute imports?

这篇关于包中的Python相对导入不在路径上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆