简体   繁体   English

如何使用ipython笔记本构建python项目?

[英]How to structure a python project with ipython notebooks?

After looking at many answers here, I still dont understand how to structure a python project with imports... 在这里查看了许多答案之后,我仍然不了解如何使用导入来构造python项目...

Let's say my dir structure is 假设我的目录结构是

myproject
   utils
      tool1.py
   datasets
      create_bla_dataset.py
   research
      mynote.ipynb

now I import tool1 from create_bla_dataset.py with 现在我从create_bla_dataset.py导入tool1

# We are in create_bla_dataset.py 
from ..utils import tool1

... define how to create a dataset

if __name__ == "__main__":
  # demo the dataset

and I can run the file with 我可以用运行文件

> cd <dir_contains_myproject>
> python -m myproject.datasets.create_bla_dataset

But now I want to import create_bla_dataset inside mynote.ipynb while opening mynote.ipynb with a jupyter notebook, but I have no idea how... 但是现在我想在用jupyter笔记本打开mynote.ipynb时在mynote.ipynb中导入create_bla_dataset,但是我不知道如何...

If I try from ..datasets import create_bla_dataset , I get ValueError: attempted relative import beyond top-level package 如果我尝试from ..datasets import create_bla_dataset尝试from ..datasets import create_bla_dataset ValueError: attempted relative import beyond top-level package

edit: I tried launching jupyter notebook from various directories but no luck, same error. 编辑:我尝试从各种目录启动jupyter笔记本,但是没有运气,同样的错误。

When you use IPython/Jupyter Notebooks you need take account that ipython server only see files from a root directory defined from where you launch the notebook instance. 使用IPython / Jupyter Notebook时,需要考虑到ipython服务器只能看到启动笔记本实例所在的根目录中的文件。 In this case, maybe you are launched directly the notebook file and not from the project root. 在这种情况下,也许直接从笔记本文件启动而不是从项目根目录启动。

Also, you can use __init__.py files. 另外,您可以使用__init__.py文件。

Updated : You can add a cell at top of the notebook. 已更新 :您可以在笔记本顶部添加一个单元格。

import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath('..')))

Then, myproject is recognized as a package and you can import as is. 然后, myproject被识别为一个包,您可以按原样导入。

from myproject.datasets.create_bla_dataset import bar
bar()
>>> 'hi foo hi bar'

This is because relative import only work in packages and if you need use as package you need to add the path where is the package. 这是因为相对导入仅在程序包中起作用,如果需要用作程序包,则需要在程序包所在的位置添加路径。

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

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