简体   繁体   English

使用Jupyter Notebook在Python中进行相对导入

[英]Relative Import in python with Jupyter notebook

I have some trouble with imports in python. 我在python中导入时遇到了一些麻烦。 I don't exactly understand why there is an error. 我不完全理解为什么会出现错误。

I am using jupyter notebook from directory notebooks. 我正在从目录笔记本使用jupyter笔记本。 I need to import function prepare_data which is situated in source/prepare_data.py 我需要导入功能prepare_data这是坐落在source/prepare_data.py

For importing i have tried to use from ..source.prepare_data import prepare_data 对于导入,我尝试from ..source.prepare_data import prepare_data ,使用from ..source.prepare_data import prepare_data

As here https://docs.python.org/3/reference/import.html (Paragraph 5.7) and python shows me an error "attempted relative import beyond top-level package". 如此处https://docs.python.org/3/reference/import.html (第5.7段),python向我显示了一个错误“尝试了超出顶级包的相对导入”。

packages 包装

You cannot import from the parent of your current working directory. 您不能从当前工作目录的父目录导入。 Easy way to solve this is working from the root path. 解决此问题的简单方法是从根路径开始工作。

In this answer you can find more info. 此答案中,您可以找到更多信息。

You can add the path of the script to your system path: 您可以将脚本的路径添加到系统路径:

sys.path.append('../source/')
from prepare_data import prepare_data

Note that this is a pretty quick-and-dirty hack. 请注意,这是一个相当肮脏的技巧。 The linked answer from @albeksdurf has some better options if you are thinking of packaging up your code. 如果您打算打包代码,则@albeksdurf的链接答案有一些更好的选择。

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

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