tags
tags

Reputation: 4059

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?

Upvotes: 3

Views: 3159

Answers (2)

Thorin Tabor
Thorin Tabor

Reputation: 41

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
    }
)

Upvotes: 4

David Smith
David Smith

Reputation: 956

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)

Upvotes: 5

Related Questions