【问题标题】:Import modules in Jupyter Notebook - Path在 Jupyter Notebook 中导入模块 - 路径
【发布时间】:2018-03-14 15:45:15
【问题描述】:

我的python项目中有以下结构:

BASE_DIRECTORY
¦- data
¦- notebooks
¦  \
¦   ***here are the jupyter notebooks***
¦   __init__.py
¦   analysis.ipynb
¦
¦- src
¦  \
¦   ***here are further modules***
¦   __init__.py
¦   configuration.py
¦

我想将 Config() 类从 configuration.py 导入到 jupyter notebook analysis.ipynb。

我试过了:

from ..src.configuration import Config

但这给了我一个ValueError:

ValueError: attempted relative import beyond top-level package

有人可以指导如何实现这一目标吗?我更喜欢使用相对路径而不是更改 PATH 变量。

我觉得 Jupyter 有一些我不知道的细节,例如参考当前路径似乎更难。

【问题讨论】:

  • 可能是因为您的根文件夹中没有 init.py,但不确定。看看吧
  • 在 jupyter see discussion here 中确实涉及到工作目录(不是说不确定?)。使用sys.path 变量是我推荐的最佳/唯一方法,@oppy 的答案对我有用。

标签: python import jupyter-notebook jupyter


【解决方案1】:

我看到你说你不想改变路径变量,但是使用 sys 来做这个给出了一个解决方案:

import sys
sys.path.append('..')

from src.configuration import Config

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 2016-03-27
    • 2021-01-08
    • 2018-10-07
    • 2021-10-04
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多