【问题标题】:Problems with relative path import in python [duplicate]python中的相对路径导入问题[重复]
【发布时间】:2019-01-31 08:18:10
【问题描述】:

我有一个具有这种目录结构的项目

我想从functions.py 从notebook01.ipynb 导入一个def。 我按照相对路径导入here的文档,研究了this stack overflow post中的答案。

我尝试写from .Modules.functions import fibonacci,(Modules 文件夹前有一个点)我收到以下错误。

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-2-be5f30231faa> in <module>
----> 1 from .Modules.functions import fibonacci

ModuleNotFoundError: No module named '__main__.Modules'; '__main__' is not a package

我尝试在 Modules 文件夹 from ..Modules.functions import fibonacci 之前添加两三个点,然后我得到了错误

ValueError                                Traceback (most recent call last)
<ipython-input-3-8d1656059c1f> in <module>
----> 1 from ..Modules.functions import fibonacci

ValueError: attempted relative import beyond top-level package

我已按照文档的建议在目录结构的每一级添加了__init__.py 文件]2 如您所见,但一点运气都没有!

我做错了什么?

【问题讨论】:

  • 试试sys.path.append(os.path.abspath(".."))。然后import Modules.functions as functions.
  • 感谢大家的回复,不知道要不要加系统的绝对路径!如果我把问题分享给一些朋友怎么办,每个人都应该更改代码以包含绝对路径吗?
  • 还有,如果用户的权限有限,无法改变路径,会发生什么? (我使用 Windows)
  • 我找到了一个很好的解决方法不添加到系统路径 here in this post

标签: python jupyter-notebook jupyter relative-path


【解决方案1】:

说实话:相对导入可能是地狱。这就是 Python 3 默认执行绝对导入 (https://docs.python.org/2.5/whatsnew/pep-328.html) 的原因。

如果你使用 Python 3 - 让你的所有包都是绝对的。

如果您仍然使用 Python 2,您可以通过在顶部添加以下行来切换默认行为:

from __future__ import absolute_import

【讨论】:

  • 感谢您的回复,其实我已经停止使用python 2,现在使用3.7。
  • 很遗憾在 python 3.x 中没有解决方案!
  • 我找到了一个很好的解决方法不添加到系统路径 here in this post
猜你喜欢
  • 1970-01-01
  • 2015-01-07
  • 2014-05-09
  • 2011-11-22
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
  • 2010-12-30
相关资源
最近更新 更多