I am new to coding so I have a question regarding Jupyter Notebook and the use of Javascript. A snippet of my current code is as follows (trueName is defined prior to this code and pickle.dump
is usually tabbed, but isn't here due to stack overflow's formatting):
%%javascript
var kernel = Jupyter.notebook.kernel;
console.log(kernel);
var command = "import pickle" + "\n" + "file_name = 'testfile'" + "\n" + "with open(file_name, 'wb') as my_file_obj:" + "\n" + "pickle.dump(trueName,my_file_obj)";
kernel.execute(command);
This works fine but for some reason when I place it into the following format:
from IPython.core.display import Javascript
Javascript("""
var kernel = Jupyter.notebook.kernel;
console.log(kernel);
var command = "import pickle" + "\n" + "file_name = 'testfile'" + "\n" + "with open(file_name, 'wb') as my_file_obj:" + "\n" + " "pickle.dump(trueName,my_file_obj)";
kernel.execute(command);""")
I obtain the following error even though the code is the same:
Javascript error adding output! SyntaxError: Invalid or unexpected token See your browser Javascript console for more details.
I had hoped to use the second method in order to bypass the magic command barrier in using something similar to !ipython somefile.ipy
to read the javascript, but for some reason the second method really doesn't like the var command
something I discovered after much testing. I have a few questions that I would greatly appreciate if I received some feedback on:
- Why does the second method provide an error due to my
var command
? I cannot figure out why this happens.(Is it true that I have to use 'textarea'? If so, how do I do this? I became lost when trying to do so myself: How to force a line break on a Javascript concatenated string?) - Is there a method for me to run Javascript magic when not directly in the notebook? I have tried running ipython on the code in a separate file with the
.ipy
ending as seen above, but it does not like running the cell magic nor the import from IPython.core.display. (This method does not work for me: How to run an IPython magic from a script (or timing a Python script)) - Is there a way for me to execute Javascript code directly (not via a file) when using a function such as
def run_javascript(code):
? Executing a cell in Jupyter gives back the code within under the argumentcode
, but I cannot find out how to run it. I have been looking around but the only answers I have found are about!node somefile.js
and other similar filename based Javascript codes. I would appreciate any help! I did have a few suggestions as to how to run python code as I would like to, but since IPython doesn't work with the Javascript I am at a loss (Python Tips: run a python script in terminal without the python command Execute python commands passed as strings in command line using python -c)