python - 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?
解决方案
在 Jupyter 中,您必须以类似 bash 的语法扩展变量,以便它们在魔术函数中工作。
这就是为什么你必须使用$符号。在你的情况下:
import os
to_include = os.path.join('example', 'file.py')
%load $to_include
推荐阅读
- python - 如何从csv文件中的日期中提取一个月?
- c# - 如何在 C# .NET 中以流的形式最好地读取 XML HttpClient 响应
- c# - 将 CSV 文件读入 c# 类列表
- ssl-certificate - 如何延长所有节点的openshift kublet-server、kublet-client证书的有效期?
- dynamics-crm - 如何在 Dynamics 365 门户中使用 FontAwesome?
- azure - 在 Azure 上下文中将文件复制到 Docker 卷
- file - Perl:以独占方式打开文件的最佳方式?
- ios - 我需要在objective-c 中使用一个swift 类,并且无法设置我的Emilos-Swift.h 桥接文件来解析objective-c 中的任何swift 类
- ruby-on-rails - 如何更改回形针附件路径?
- c++ - 如何在 C++ Win32 应用程序中检测 ALT 按键而不管焦点