[英]How to load custom cell magic from a relative directory (in Jupyter notebook)?
I have a custom cell magic which I need to load from a relative path.我有一个自定义单元格魔法,我需要从相对路径加载它。 I can do so when the module directory is in the same place as the notebook.
当模块目录与笔记本位于同一位置时,我可以这样做。 However, it doesn't work when I have a more complex directory structure.
但是,当我有更复杂的目录结构时,它不起作用。
It works if the directory structure is this:如果目录结构是这样的,它就可以工作:
test_custom_magic\
|-custom_magic_code\
|-__init__.py
|-etcetc.py
|-test_notebook.ipy
In this scenario, I just do a %reload_ext custom_magic_code
and my code works.在这种情况下,我只执行
%reload_ext custom_magic_code
并且我的代码有效。
However, now that I'm done writing and testing the code, I'm trying to use it in a more complex directory:但是,现在我已经完成了代码的编写和测试,我正在尝试在更复杂的目录中使用它:
important_project\
|-notebooks\
|-do_something_important.ipy
|-do_something_else_important.ipy
|-custom_magic_code\
|-__init__.py
|-etcetc.py
In do_something_important.ipy
, I can't just %reload_ext custom_magic_code
.在
do_something_important.ipy
,我不能只是%reload_ext custom_magic_code
。 I get a ModuleNotFoundError
.我得到一个
ModuleNotFoundError
。
If I try %reload_ext ../custom_magic_code
(or some other nested directory level), I get this error: TypeError: the 'package' argument is required to perform a relative import for '../custom_magic_code'
如果我尝试
%reload_ext ../custom_magic_code
(或其他一些嵌套目录级别),我会收到此错误: TypeError: the 'package' argument is required to perform a relative import for '../custom_magic_code'
How can I solve this problem?我怎么解决这个问题? Please note that my custom magic code is good enough for me to run locally.
请注意,我的自定义魔术代码足以让我在本地运行。 I'm not quite ready to package it and install via pip/conda/nbextension just yet (and I'm trying to avoid learning that anyway, until I can get my current code working).
我还没有准备好通过 pip/conda/nbextension 打包和安装(而且我试图避免学习,直到我可以让我当前的代码工作)。
So I ended up using the following code to include relevant directory among the paths python checks to find libraries:所以我最终使用以下代码在路径中包含相关目录 python 检查以查找库:
module_path = os.path.abspath(os.path.join('../..'))
if module_path not in sys.path:
sys.path.append(module_path)
Seems to work!似乎工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.