首页 > 解决方案 > Jupyter Lab/Notebook magic command %load with platform independent path

问题描述

I am trying to develop a Jupyter notebook that includes cells that have the %load magic command to load code from elsewhere. This code is not in the same directory as where the notebook is. I want this to work on Windows, Linux and Mac, so path separators should sometimes be '\' and sometimes '/'.

Usually I would solve this by using os.path.join. Nevertheless, when I do this in a line with the load command, the notebook just evaluates the path, and doesn't actually load the code. Is there a way of doing this, other than first just changing the working directory and changing it back after executing the code that I loaded?

Brief example:

import os
%load os.path.join('example', 'file.py')

This gives an error as it will actually search for a file with the name os.path.join('example', 'file.py'). If I first evaluate that and put the result in load I get:

import os
to_include = os.path.join('example', 'file.py')
print(to_include)
%load to_include

That evaluates to just

# %load to_include
example/file.py

But obviously I want the content of that file loaded, not the path + filename. What am I doing wrong?

标签: pythonloadjupyter-notebookos.pathipython-magic

解决方案


在 Jupyter 中,您必须以类似 bash 的语法扩展变量,以便它们在魔术函数中工作。

这就是为什么你必须使用$符号。在你的情况下:

import os
to_include = os.path.join('example', 'file.py')
%load $to_include

推荐阅读