在不同的 jupyter 笔记本之间共享变量

Share variables between different jupyter notebooks

我有两个不同的 Jupyter 笔记本,运行 在同一台服务器上。我想做的是通过另一个笔记本访问一个笔记本的一些(只有少数)变量(我必须比较算法的两个不同版本是否给出相同的结果,基本上)。有办法吗?

谢谢

如果您只需要一些快速又肮脏的东西,您可以使用 pickle 模块使数据持久化(将其保存到文件中),然后让您的其他笔记本获取它。例如:

import pickle

a = ['test value','test value 2','test value 3']

# Choose a file name
file_name = "sharedfile"

# Open the file for writing
with open(file_name,'wb') as my_file_obj:
    pickle.dump(a,my_file_obj)   

# The file you have just saved can be opened in a different session
# (or iPython notebook) and the contents will be preserved.

# Now select the (same) file to open (e.g. in another notebook)
file_name = "sharedfile"
# Open the file for reading
file_object = open(file_Name,'r')  
# load the object from the file into var b
b = pickle.load(file_object)  

print(b)
>>> ['test value','test value 2','test value 3']

2个jupyter notebook之间,可以使用%store命令

在第一个 jupyter notebook 中:

data = 'string or data-table to pass'
%store data
del data

在第二个 jupyter notebook 中:

%store -r data
data

您可以在 here 找到更多信息。

您可以使用相同的 magic commands 来执行 this.The Cell magic: IPython notebook 中的 %%cache 可用于缓存 long 的结果和输出-持久泡菜文件中的持久计算。当笔记本中的某些计算很长并且您想轻松地将结果保存在文件中时很有用。

要在笔记本中使用它,您需要先安装模块 ipycache,因为此 Cell 魔术命令不是内置魔术命令。

然后在笔记本中加载模块:

%load_ext ipycache

然后,创建一个单元格:

%%cache mycache.pkl var1 var2
var1 = 1  # you can put any code you want at there,
var2 = 2  # just make sure this cell is not empty.

当你第一次执行这个单元格时,代码被执行,变量 var1 和 var2 与输出一起保存在当前目录的 mycache.pkl 中。仅当您使用 IPython 的开发版本时才会保存丰富的显示输出。当您再次执行此单元格时,将跳过代码,从文件加载变量并将其注入命名空间,并在笔记本中恢复输出。

或者使用 $file_name 而不是 mycache.pkl,其中 file_name 是一个变量,其中包含用于缓存的文件的路径。

使用--force-f选项强制执行单元格并覆盖文件。

使用--read-r 选项来阻止单元格的执行并始终从缓存中加载变量。如果文件不存在则引发异常。

参考: ipycache and the example notebook

的 github 存储库