3

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?

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the input David. After some search, it appears there are several way to 'interface' as such python and js. some people use framework such as jinja2. it is also possible using simply 'tricks' such as in this blog entry I wrote: quantcorner.wordpress.com/2014/10/13/…
What you say is true - there is also a very good discussion entitled IPython Notebook: Javascript/Python Bi-directional Communication. I tried to tailor my answer to fit your question directly.
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.