【问题标题】:Python Relative Import in Jupyter NotebookJupyter Notebook 中的 Python 相对导入
【发布时间】:2020-07-18 09:24:38
【问题描述】:

假设我有以下结构:

 dir_1
 ├── functions.py
 └── dir_2
     └── code.ipynb

在code.ipynb,我只是想访问functions.py 中的一个函数并尝试了这个:

from ..functions import some_function

我得到错误:

attempted relative import with no known parent package

我检查了一堆类似的帖子,但还没有弄清楚...我正在从 conda env 运行 jupyter notebook,我的 python 版本是 3.7.6。

【问题讨论】:

  • 笔记本相对于其他文件的位置在哪里?
  • 示例中的笔记本为code.py。我会更新问题。

标签: python jupyter-notebook anaconda relative-import


【解决方案1】:

在你的笔记本上做:

import os, sys
dir2 = os.path.abspath('')
dir1 = os.path.dirname(dir2)
if not dir1 in sys.path: sys.path.append(dir1)
from functions import some_function

【讨论】:

    【解决方案2】:

    jupyter notebook 从 sys.path 中的当前工作目录开始。 见sys.path

    ...包含用于调用 Python 解释器的脚本的目录。

    如果您的实用程序函数在父目录中,您可以这样做:

    import os, sys
    parent_dir = os.path.abspath('..')
    # the parent_dir could already be there if the kernel was not restarted,
    # and we run this cell again
    if parent_dir not in sys.path:
        sys.path.append(parent_dir)
    from functions import some_function
    

    【讨论】:

      【解决方案3】:

      你可以使用sys.path.append('/path/to/application/app/folder')然后尝试导入

      【讨论】:

      • 谢谢!我真的很想避免说明明确的路径。有没有办法解决这个问题?为什么会出现上述错误?
      • 我相信问题是由于您的相对导入。您可能想尝试类似 python3 -m dir_2/code.py
      • 不确定我是否理解。我正在运行一个 jupyter 笔记本,重点是我想使用相对路径并避免显式路径。
      • 为了能够使用相对路径,您应该在包中工作。 '换句话说,解析模块的算法是基于 name 和 package 变量的值。在您的情况下,您没有包,因此 package 没有。您需要有 init.py 才能使您的目录成为一个包。这里详细介绍了两种不同的解决方案:napuzba.com/a/import-error-relative-no-parent/p2
      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2016-12-15
      • 1970-01-01
      • 2021-10-29
      • 2016-10-04
      相关资源
      最近更新 更多