【问题标题】:Calling external py modules from jupyter notebooks从 jupyter 笔记本调用外部 py 模块
【发布时间】:2020-01-18 17:57:59
【问题描述】:

我有这样的项目结构

我在utils.py 中有一些函数我想在aNotebook 中使用,所以在我的项目上运行pip install --editable 命令并将以下内容放在笔记本的第一个单元格中

    %load_ext autoreload
    %autoreload 2

我相信这应该允许我这样做

    import src.constants
    from src.utils import write_data

    write_data(....)

但我遇到了一个问题,即constants.py 中定义的 constants 似乎不成立。换句话说,utils.py 中依赖于 constants 的函数在运行时没有被定义。

更重要的是,为了确保utils.py 中的函数可以使用常量,而不需要用户知道它们是必需的,utils.py 导入了constants.py

我的问题,是否有关于如何将 Jupyter 笔记本与普通的旧 python 模块一起使用以便两者都可以驻留在同一个项目中的入门指南?对于应该很容易的事情,这似乎需要做很多工作。

编辑:添加 MVC 和错误

*** src\utils.py 的内容

def test1():
    return 'got to the test program'

【问题讨论】:

  • 我理解正确,在您的 utils.py 中运行 from constants import *,当您从 utils.py 导入时,这些常量未定义?
  • 是的,它们在 Jupyter 笔记本中是未定义的,并且它们似乎没有粘在代码中
  • 您可以运行一个示例并在您的帖子中添加回溯错误吗?

标签: python jupyter-notebook


【解决方案1】:

我想通了。

import os
import sys
# This adds the project root to the searchpath
sys.path.append(os.path.pardir)

# Then I can use 
from src.utils import test1

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 2021-04-24
    • 2018-01-13
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多