IPython:将 Javascript 脚本添加到 IPython 笔记本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16852885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:13:46  来源:igfitidea点击:

IPython: Adding Javascript scripts to IPython notebook

javascripthtmlipythonipython-notebook

提问by Tarun Gaba

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

作为项目的一部分,我需要在 IPython 模块中嵌入一些 javascript。这就是我想要做的:

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

My Gl.js looks like this

我的 Gl.js 看起来像这样

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.

有什么方法可以让我在笔记本中嵌入“Gl.js”和其他这样的外部脚本,这样我就不必每次尝试执行一些需要该库的 Javascript 代码时将它们作为“lib”参数包含在内。

回答by Alex

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

作为一个非常短期的解决方案,您可以利用 IPythondisplay()HTML()函数将一些 JavaScript 注入页面。

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

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

尽管我不推荐使用官方custom.js方法,但有时我确实发现快速测试某些内容或动态生成小的 JavaScript 片段很有用。

回答by Anton Tarasenko

Embedding D3 in an IPython Notebook

在 IPython Notebook 中嵌入 D3

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

IPython Notebook:Javascript/Python 双向通信

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

一篇更详尽的文章,解释了如何在 JavaScript 中访问 Python 变量,反之亦然。

回答by Matt

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

至少现在不是通过安装包来开箱即用的。这样做的方法是使用custom.js和 jQuerygetScript将 js 注入笔记本。

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 staticfolder in user profile is mergedwith webserver static assets allowing you to access any file that are in this folder by asking for the right url.

您应该知道的是,static用户配置文件中的文件夹merged包含网络服务器静态资产,允许您通过请求正确的 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

几个小时前,在 IPython 每周视频“实验室会议”上也有人问过这个问题,在 youtube 上直播和disponible(你可能有更长的答案),我在这里与问题的作者展开了讨论

回答by Bill Mills

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:

首先,在 中.ipython/<profile>/static/custom/myScript.js,我们做了一些 require.js 魔法:

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/<profile>/static/custom/custom.js,将它们拖到持久的东西中:

$([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

是的,我是一个在 window 对象上扔东西的可怕的人,你认为合适的命名空间。但是现在在笔记本中,一个像

%%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.jsto 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!

应该完全按照它看起来应该做的,而无需用户显式导入您的 JS。我很想看到这个简单的解决方案(PLZ开发者才能PLZ必须$.getScript('/static/custom/util.js');custom.js加载了一堆的全球JS功能) -但这是我已经得到了现在最好的。抛开这个唱歌跳舞不谈,给IPython notebook团队大赞,这是一个很棒的平台!

回答by Ben Mares

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:

出于某种原因,我在使用 IPython.display.Javascript 时遇到了问题。这是我的替代方案,它可以处理导入外部 .js 文件和运行自定义代码:

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")')