Advertisement
bgschaid

Adapted "Accessing Python Output In Javascript"

May 19th, 2014
1,740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. # Example from http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/ adapted for IPython 2.0
  2. # Add an input form similar to what we saw above
  3. input_form = """
  4. <div style="background-color:gainsboro; border:solid black; width:600px; padding:20px;">
  5. Code: <input type="text" id="code_input" size="50" height="2" value="sin(pi / 2)"><br>
  6. Result: <input type="text" id="result_output" size="50" value="1.0"><br>
  7. <button onclick="exec_code()">Execute</button>
  8. </div>
  9. """
  10.  
  11. # here the javascript has a function to execute the code
  12. # within the input box, and a callback to handle the output.
  13. javascript = """
  14. <script type="text/Javascript">
  15.    function handle_output(out){
  16. //       console.log(out_type);
  17.        console.log(out);
  18.        var res = null;
  19.         // if output is a print statement
  20.        if(out.msg_type == "stream"){
  21.            res = out.content.data;
  22.        }
  23.        // if output is a python object
  24.        else if(out.msg_type === "pyout"){
  25.            res = out.content.data["text/plain"];
  26.        }
  27.        // if output is a python error
  28.        else if(out.msg_type == "pyerr"){
  29.            res = out.content.ename + ": " + out.content.evalue;
  30.        }
  31.        // if output is something we haven't thought of
  32.        else{
  33.            res = "[out type not implemented]";  
  34.        }
  35.        document.getElementById("result_output").value = res;
  36.    }
  37.    
  38.    function exec_code(){
  39.        var code_input = document.getElementById('code_input').value;
  40.        var kernel = IPython.notebook.kernel;
  41.        var callbacks = { 'iopub' : {'output' : handle_output}};
  42.        document.getElementById("result_output").value = "";  // clear output box
  43.        var msg_id = kernel.execute(code_input, callbacks, {silent:false});
  44.        console.log("button pressed");
  45.        // IPython.notebook.clear_output();
  46.    }
  47. </script>
  48. """
  49.  
  50. HTML(input_form + javascript)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement