Cannot Get Jupyter Notebook To Access Javascript Variables
Solution 1:
I looked further into this and found a solution, but it really is a hack that might break with future versions of Jupyter notebook. I hope someone has a more future-proof answer.
The idea is to avoid the catch-22 that the code example creates by using the stdin channel of the Jupyter messaging system (https://jupyter-client.readthedocs.io/en/stable/messaging.html).
The code works as follows:
when a code cell contains an input('prompt-text')
command, this is sent to the notebook client over a dedicated stdin channel, which is independent of the normal cell execution stream. So I 'hacked' the code of the notebook client to capture input requests that are sent by the kernel, and provide an answer without prompting the user.
display(Javascript("""
const CodeCell = window.IPython.CodeCell;
CodeCell.prototype.native_handle_input_request = CodeCell.prototype.native_handle_input_request || CodeCell.prototype._handle_input_request
CodeCell.prototype._handle_input_request = function(msg) {
try {
// only apply the hack if the command is valid JSON
const command = JSON.parse(msg.content.prompt);
const kernel = IPython.notebook.kernel;
// in the future: send the command to a server and wait for a response.
// for now: specify a 5 second delay and return 'RESPONSE'
setTimeout(() => { kernel.send_input_reply('RESPONSE') },5000)
} catch(err) {
console.log('Not a command',msg,err);
this.native_handle_input_request(msg);
}
}
"""))
response = input(json.dumps({"do":"something"}))
print(response)
This blocks execution for 5 seconds, then prints 'RESPONSE' and continues.
Post a Comment for "Cannot Get Jupyter Notebook To Access Javascript Variables"