简体   繁体   中英

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?

In Jupyter you have to expand variables in a bash-like syntax for them to work in magic functions.

That's why you will have to use the $ sign. In your case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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