IPython: Adding Javascript scripts to IPython note

2019-03-11 05:33发布

问题:

As a part of a project, I need to embedd some javascripts inside an IPython module. This is what I want to do:

from IPython.display import display,Javascript
Javascript('echo("sdfds");',lib='/home/student/Gl.js')

My Gl.js looks like this

function echo(a){
alert(a);
}

Is there some way so that I can embed "Gl.js" and other such external scripts inside the notebook, such that I dont have to include them as 'lib' argument everytime I try to execute some Javascript code which requires to that library.

回答1:

As a very short-term solution, you can make use of the IPython display() and HTML() functions to inject some JavaScript into the page.

from IPython.display import display, HTML
js = "<script>alert('Hello World!');</script>"
display(HTML(js))

Although I do not recommend this over the official custom.js method, I do sometimes find it useful to quickly test something or to dynamically generate a small JavaScript snippet.



回答2:

Embedding D3 in an IPython Notebook

  • https://blog.thedataincubator.com/2015/08/embedding-d3-in-an-ipython-notebook/

To summarize the code.

Import the script:

%%javascript
require.config({
  paths: {
      d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min'
  }
});

Add an element like this:

%%javascript
element.append("<div id='chart1'></div>");

Or this:

from IPython.display import Javascript
#runs arbitrary javascript, client-side
Javascript("""
           window.vizObj={};
           """.format(df.to_json()))

IPython Notebook: Javascript/Python Bi-directional Communication

  • http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/

A more extensive post explaining how to access Python variables in JavaScript and vice versa.



回答3:

Not out of the box by installing a package, at least for now. The way to do it is to use custom.js and jQuery getScript to inject the js into the notebook.

I explicitly stay vague on how to do it, as it is a dev feature changing from time to time.

What you should know is that the static folder in user profile is merged with webserver static assets allowing you to access any file that are in this folder by asking for the right url.

Also this question has been asked a few hours ago on IPython weekly video "lab meeting" broadcasted live and disponible on youtube (you might have a longer answer), I've opened discussion with the author of the question here



回答4:

I've been fighting with this problem for several days now, here's something that looks like it works; buyer beware though, this is a minimal working solution and it's neither pretty nor optimal - a nicer solution would be very welcome!

First, in .ipython/<profile>/static/custom/myScript.js, we do some require.js magic:

define(function(){

    var foo = function(){
            console.log('bar');
        }

    return {
        foo : foo
    }
});

Copy this pattern for as many functions as you like. Then, in .ipython/<profile>/static/custom/custom.js, drag those out into something persistent:

$([IPython.events]).on('notebook_loaded.Notebook', function(){

    require(['custom/myScript'], function(custom){
        window.foo = custom.foo;
    } );

});

Yes, I am a horrible person for throwing stuff on the window object, namespace things as you deem appropriate. But now in the notebook, a cell like

%%javascript

foo();

should do exactly what it looks like it should, without the user having to explicitly import your JS. I would love to see a simpler solution for this (plz devs can we plz have $.getScript('/static/custom/util.js'); in custom.js to load up a bunch of global JS functions) - but this is the best I've got for now. This singing and dancing aside, HUGE ups to the IPython notebook team, this is an awesome platform!



回答5:

For some reason, I have problems with IPython.display.Javascript. Here is my alternative, which can handle both importing external .js files and running custom code:

from IPython.display import display, HTML

def javascript(*st,file=None):
    if len(st) == 1 and file is None:
        s = st[0]
    elif len(st) == 0 and file is not None:
        s = open(file).read()
    else:
        raise ValueError('Pass either a string or file=.')
    display(HTML("<script type='text/javascript'>" + s + "</script>"))

Usage is as follows:

javascript('alert("hi")')
javascript(file='Gl.js')
javascript('echo("sdfds")')