Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python-defined variables in javascript code within ipython notebook?

Say I made complex numeric calculations with Scipy factories, using the Ipython notebook. Now, I want to call variables resulting from calculations with Scipy from code in Javascript (still within IPYNB).

Below is a simplistic illustration of what I am willing to accomplish:

# Get a vector of 4 normal random numbers using numpy - the variable 'rnd'
import numpy as np
mu, sig = 0.05, 0.2
rnd = np.random.normal(loc=mu, scale=sig, size=4)

Now, I want to use the variable rnd above in Javascript, for illustrative purpose:

%%javascript
element.append(rnd);

The lines above returns a message error: ReferenceError: rnd is not defined.

Then, how can one use a python variable in javascript code within the Ipython Notebook?

like image 906
tagoma Avatar asked Jun 22 '26 13:06

tagoma


2 Answers

It may not be possible to do this with the %%Javascript cell magic. However you can use the IPython.display.Javascript(...) method to inject Python strings into the browser output area. Here's a modification of your code fragment that seems to answer your question.

from IPython.display import Javascript

import numpy as np
mu, sig = 0.05, 0.2
rnd = np.random.normal(loc=mu, scale=sig, size=4)

## Now, I want to use the variable rnd above in Javascript, for illustrative purpose:

javascript = 'element.append("{}");'.format(str(rnd))

Javascript(javascript)

Paste this code into an input cell and each time you execute the cell a new and different array of random numbers will be displayed in the output cell.

(Code was tested with IPython version 2.2)

like image 108
David Smith Avatar answered Jun 25 '26 07:06

David Smith


Arbitrary Python (including retrieving the value of variables) can be executed from the JavaScript side of things in IPython, although it is a bit messy. The following code works for me in IPython 3.1 and Python 2.7:

%%javascript
IPython.notebook.kernel.execute(
    "<PYTHON CODE TO EXECUTE HERE>", 
    {
        iopub: {
            output: function(response) {
                // Print the return value of the Python code to the console
                console.log(response.content.data["text/plain"]);
            }
        }
    },
    {
        silent: false, 
        store_history: false, 
        stop_on_error: true
    }
)
like image 30
Thorin Tabor Avatar answered Jun 25 '26 07:06

Thorin Tabor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!