我有两个不同的Jupyter笔记本,在同一台服务器上运行。我想要做的是通过另一个笔记本访问一个笔记本的一些(只有少数几个)变量(我必须比较两个不同版本的算法是否给出相同的结果,基本上)。有没有办法做到这一点?
由于
答案 0 :(得分:24)
在2个jupyter笔记本之间,您可以使用%store命令。
在第一个jupyter笔记本中:
data = 'string or data-table to pass'
%store data
del data
在第二个jupyter笔记本中:
%store -r data
data
您可以在here找到更多信息。
答案 1 :(得分:7)
如果你只需要快速的东西,你可以使用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 :(得分:2)
您可以使用相同的magic commands
来执行此操作.IPython笔记本中的Cell magic
:%%cache
可用于在持久性pickle文件中缓存持久计算的结果和输出。当笔记本中的某些计算很长并且您希望将结果轻松保存在文件中时很有用。
要在笔记本中使用它,您需要先安装模块ipycache
,因为此Cell magic命令不是内置的魔术命令。
然后将模块加载到笔记本中:
%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
选项阻止单元格的执行,并始终从缓存中加载变量。如果文件不存在,则会引发异常。
REF: ipycache和example notebook
的github存储库