简体   繁体   English

从 jupyter notebooks 调用外部 py 模块

[英]Calling external py modules from jupyter notebooks

I have a project structure like this我有一个这样的项目结构

在此处输入图片说明

I have some functions in utils.py which I want to use in aNotebook , so ran the pip install --editable command on my project and put the following in the first cell of the notebook我在utils.py有一些我想在aNotebook使用的aNotebook ,所以在我的项目上运行pip install --editable命令并将以下内容放在笔记本的第一个单元格中

    %load_ext autoreload
    %autoreload 2

This I believe should allow me to do我相信这应该允许我做

    import src.constants
    from src.utils import write_data

    write_data(....)

But I'm having an issue where the constants defined in constants.py don't seem to stick.但是我遇到了一个问题, constants.py 中定义的constants.py似乎不存在。 In other words, the functions in utils.py that are depending on the constants are not being defined at runtime.换句话说, utils.py中依赖于常量的函数不是在运行时定义的。

What's more, in order to ensure that the constants are available to the function in utils.py without requiring the user to know they are required, utils.py imports the constants.py此外,为了确保常量可用于utils.py的函数而不需要用户知道它们是必需的, utils.py导入了constants.py

My question , is there a primer on how to use Jupyter notebooks with plain old python modules such that both can reside in the same project?我的问题是,是否有关于如何将 Jupyter 笔记本与普通的旧 python 模块一起使用以便两者可以驻留在同一个项目中的入门指南? This seems like a lot of work for something that should be easy.对于应该很容易的事情,这似乎需要做很多工作。

EDIT: Adding MVC and error编辑:添加MVC和错误

在此处输入图片说明

在此处输入图片说明

*** contents of src\\utils.py *** src\\utils.py 的内容

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

I figured it out.我想到了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM