gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:34:14 28 4
gpt4 key购买 nike

如何将 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 的最佳方法。

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

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

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

最佳答案

答案在您提供的链接中:

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 来实现这一点。但到那时,您在绝对进口方面取得了什么成就?

关于不在路径上的包内的 Python 相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9011545/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com