The key functionality needed for interaction between javascript and the IPython kernel
is the kernel object in the IPython Javascript package. Use IPython.display.HTML
for embedded html and javascript display
var kernel = IPython.notebook.kernel;
kernel.execute(command);
or with a callback function in javascript
var kernel = IPython.notebook.kernel;
function callback(out_type, out_data){
// do_something
}
kernel.execute(command, {"output": callback});
from IPython.display import HTML
input_form = """
<div style="background-color:gainsboro; border:solid black; width:300px; padding:20px;">
Variable Name: <input type="text" id="var_name" value="foo"><br>
Variable Value: <input type="text" id="var_value" value="bar"><br>
<button onclick="set_value()">Set Value</button>
</div>
"""
javascript = """
<script type="text/Javascript">
function set_value(){
var var_name = document.getElementById('var_name').value;
var var_value = document.getElementById('var_value').value;
var command = var_name + " = '" + var_value + "'";
console.log("Executing Command: " + command);
var kernel = IPython.notebook.kernel;
kernel.execute(command);
}
</script>
"""
HTML(input_form + javascript)
print foo
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-512cd49e65f5> in <module>() ----> 1 print foo NameError: name 'foo' is not defined
# Add an input form similar to what we saw above
input_form = """
<div style="background-color:gainsboro; border:solid black; width:600px; padding:20px;">
Code: <input type="text" id="code_input" size="50" height="2" value="sin(pi / 2)"><br>
Result: <input type="text" id="result_output" size="50" value="1.0"><br>
<button onclick="exec_code()">Execute</button>
</div>
"""
# here the javascript has a function to execute the code
# within the input box, and a callback to handle the output.
javascript = """
<script type="text/Javascript">
function handle_output(out_type, out){
console.log(out_type);
console.log(out);
var res = null;
// if output is a print statement
if(out_type == "stream"){
res = out.data;
}
// if output is a python object
else if(out_type === "pyout"){
res = out.data["text/plain"];
}
// if output is a python error
else if(out_type == "pyerr"){
res = out.ename + ": " + out.evalue;
}
// if output is something we haven't thought of
else{
res = "[out type not implemented]";
}
document.getElementById("result_output").value = res;
}
function exec_code(){
var code_input = document.getElementById('code_input').value;
var kernel = IPython.notebook.kernel;
var callbacks = {'output' : handle_output};
document.getElementById("result_output").value = ""; // clear output box
var msg_id = kernel.execute(code_input, callbacks, {silent:false});
console.log("button pressed");
}
</script>
"""
HTML(input_form + javascript)