[英]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.我正在尝试开发一个 Jupyter 笔记本,其中包含具有 %load 魔法命令以从其他地方加载代码的单元格。 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 '/'.
我希望它可以在 Windows、Linux 和 Mac 上运行,所以路径分隔符有时应该是“\\”,有时是“/”。
Usually I would solve this by using os.path.join.通常我会通过使用 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.
尽管如此,当我使用 load 命令执行此操作时,笔记本只会评估路径,而不会实际加载代码。 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').这会产生错误,因为它实际上会搜索名称为 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.在 Jupyter 中,您必须以类似 bash 的语法扩展变量,以便它们在魔术函数中工作。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.