Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share variables between different jupyter notebooks

I have two different Jupyter notebooks, running on the same server. What I would like to do is to access some (only a few of them) of the variables of one notebook through the other notebook (I have to compare if the two different versions of the algorithm give the same results, basically). Is there a way to do this?

Thanks

like image 572
user22710 Avatar asked Mar 11 '16 08:03

user22710


People also ask

How do you access variables from another Jupyter notebook?

Notebooks in Jupyter Lab can share the same kernel. In your notebook you can choose the kernel of another notebook and variables from the other notebook will be available in both notebooks. Click on the button that describes your current kernel.

How do you link two Jupyter notebooks?

Running a Jupyter Notebook from Another Jupyter NotebookFrom the left Sidebar, select and right-click on the Jupyter notebook that has to be run from another notebook. From the context menu, select Copy Path. Open the Jupyter notebook from which you want to run another notebook. Click Run.


2 Answers

Between 2 jupyter notebook, you can use the %store command.

In the first jupyter notebook:

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

In the second jupyter notebook:

%store -r data data 

You can find more information at here.

like image 162
chabir Avatar answered Sep 28 '22 18:09

chabir


If you only need something quick'n dirty, you can use the pickle module to make the data persistent (save it to a file) and then have it picked up by your other notebook. For example:

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'] 
like image 28
alfredoc Avatar answered Sep 28 '22 17:09

alfredoc