导入iPython自定义小部件函数(文件结构?)

Import a iPython Custom Widget Function (File Structure?)

本文关键字:文件结构 函数 iPython 自定义 小部 导入      更新时间:2023-09-26

我试图按照这个例子和本教程制作一个D3小部件,当调用函数时,它会向小部件显示D3 HTML代码。我可以使用%%javascript使它在笔记本单元格中发挥作用,但这对最终用户来说会很麻烦。

如何将Python D3Widget类定义和Javascript D3View渲染代码移动到外部文件,以便用户可以简单地导入文件并调用函数?

我希望最终结果是这样的,用户可以简单地导入一个函数并调用它

组织您的代码

在您的笔记本根文件夹中为您的新小部件创建一个包。例如,您可以使用以下目录结构:

helloworld/
    __init__.py
    helloworld_widget.py
    helloworldjs/
        helloworld.view.js
        css/
            helloworld.css

对服务器端进行编程

在helloworld/helloworld_idget.py中,放入您的Python类:

from ipywidgets import widgets
from traitlets import Unicode
class HelloWorldWidget(widgets.DOMWidget):
    _view_module = Unicode("nbextensions/helloworld/helloworld_view", sync=True)
    _view_name = Unicode('HelloWorldView', sync=True)

这就是你的python代码。

创建Javascript视图

在helloworld/helloworld.view.js程序中,您的客户端:

define(["nbextensions/widgets/widgets/js/widget"], function(widget) {
    var HelloWorldView = widget.DOMWidgetView.extend({
        render: function(){
            this.$el.text("Hello world");
        },
    });
    return {HelloWorldView: HelloWorldView}
});

很简单,不是吗?最后不能不提

将客户端部署到笔记本的扩展文件夹

为此,您可以在init.py中编程一个函数,并在每次修改Javascript视图中的内容时在笔记本中执行它。

我使用的这个与以下非常相似:

def notebook_install(overwrite=True, user=True):
    import os
    from notebook import install_nbextension
    from notebook.services.config import ConfigManager
    from IPython.display import display, Javascript
    js_path = os.path.join( os.path.dirname(__file__), 'helloworldjs')
    install_nbextension(js_path, overwrite=overwrite,
                        symlink=False, verbose=0, user=user)

现在,您应该能够在笔记本中执行以下操作:

from helloworld.helloworld_widget import HelloWorldWidget
hello = HellowWorldWidget()
hello

享受吧!

仔细阅读这篇文章也会有所帮助:https://carreau.gitbooks.io/jupyter-book/content/notebook-extensions.html