简体   繁体   English

将pycharm项目导入jupyter notebook

[英]Import pycharm project into jupyter notebook

I am using Pycharm to develop a python package and would like to use Jupyter notebooks to interact with the modules.我正在使用 Pycharm 开发一个 python 包,并希望使用 Jupyter notebooks 与模块进行交互。

My project structure is as follows :我的项目结构如下:

project/notebooks/my_notebook.ipynb
project/module/__init__.py
project/module/core.py
project/tests/...

I run my_notebook.ipynb in the browser but cannot figure out how to import the content of the python module.我在浏览器中运行my_notebook.ipynb但不知道如何导入 python 模块的内容。 Anything like from module import foo does not work out of the box.from module import foo这样的东西不能开箱即用。 I came accross this blog post which involves installing the source code as an editable Pip package but I am wondering if there is another way to make it work that does not involves installing the package ?我遇到了这篇博文,其中涉及将源代码安装为可编辑的 Pip 包,但我想知道是否有另一种方法可以使其工作而不涉及安装包?

You just need to get that directory into your path inside the notebook:您只需要将该目录放入笔记本内的路径中:

eg:例如:

import sys

# make sure to use position 1
sys.path.insert(1, "/Users/foo/bar/project/")
from module.core import foo

It's important to use position 1 as using position 0 may break sys.path: docs使用位置 1 很重要,因为使用位置 0 可能会破坏 sys.path: docs

Also note you should make sure you are using the same virtualenv (or conda env) for your notebook that your pycharm project is using, or else you might have unanticipated conflicts另请注意,您应该确保为您的 pycharm 项目正在使用的笔记本使用相同的virtualenv(或 conda env),否则您可能会遇到意外冲突

In my opinion is bad practice to hardcode a specific path into the notebook code.在我看来,将特定路径硬编码到笔记本代码中是不好的做法。 Instead I would add the root project folder to PYTHONPATH when starting up your Jupyter notebook server, either directly from the project folder like so相反,我会在启动 Jupyter 笔记本服务器时将根项目文件夹添加到 PYTHONPATH,或者直接从项目文件夹中添加

env PYTHONPATH=`pwd` jupyter notebook

or if you are starting it up from somewhere else, like so或者如果你是从其他地方启动它,就像这样

env PYTHONPATH=/Users/foo/bar/project/ jupyter notebook

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

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