Jupyter Notebook 中的变量资源管理器

Variable Explorer in Jupyter Notebook

Jupyter (IPython) 中是否有像 Spyder 中那样的变量浏览器?每次我 运行 通过测试代码时都必须一直打印变量列表,这是非常不舒服的。

这个功能实现了吗?如果可以,如何启用?

这可能对您有所帮助,尽管它不完全是 Spyder 提供的,而且要简单得多:

要获取所有当前定义变量的列表,运行 who :

In [1]: foo = 'bar'

In [2]: who
foo

更多详情,运行 whos:

In [3]: whos
Variable   Type    Data/Info
----------------------------
foo        str     bar

有关内置函数的完整列表,请参阅 Magic Commands

更新

向下滚动到标记为更新的部分,以获得更简单的方法。

旧答案

这是一本关于如何制作自己的笔记本Variable Inspector。我认为它是在 jupyter notebook 被称为 ipython notebook 时写回来的,但它适用于最新版本。

我将 post 下面的代码以防 link 中断。

import ipywidgets as widgets # Loads the Widget framework.
from IPython.core.magics.namespace import NamespaceMagics # Used to query namespace.

# For this example, hide these names, just to avoid polluting the namespace further
get_ipython().user_ns_hidden['widgets'] = widgets
get_ipython().user_ns_hidden['NamespaceMagics'] = NamespaceMagics

class VariableInspectorWindow(object):
    instance = None

def __init__(self, ipython):
    """Public constructor."""
    if VariableInspectorWindow.instance is not None:
        raise Exception("""Only one instance of the Variable Inspector can exist at a 
            time.  Call close() on the active instance before creating a new instance.
            If you have lost the handle to the active instance, you can re-obtain it
            via `VariableInspectorWindow.instance`.""")

    VariableInspectorWindow.instance = self
    self.closed = False
    self.namespace = NamespaceMagics()
    self.namespace.shell = ipython.kernel.shell

    self._box = widgets.Box()
    self._box._dom_classes = ['inspector']
    self._box.background_color = '#fff'
    self._box.border_color = '#ccc'
    self._box.border_width = 1
    self._box.border_radius = 5

    self._modal_body = widgets.VBox()
    self._modal_body.overflow_y = 'scroll'

    self._modal_body_label = widgets.HTML(value = 'Not hooked')
    self._modal_body.children = [self._modal_body_label]

    self._box.children = [
        self._modal_body, 
    ]

    self._ipython = ipython
    self._ipython.events.register('post_run_cell', self._fill)

def close(self):
    """Close and remove hooks."""
    if not self.closed:
        self._ipython.events.unregister('post_run_cell', self._fill)
        self._box.close()
        self.closed = True
        VariableInspectorWindow.instance = None

def _fill(self):
    """Fill self with variable information."""
    values = self.namespace.who_ls()
    self._modal_body_label.value = '<table class="table table-bordered table-striped"><tr><th>Name</th><th>Type</th><th>Value</th></tr><tr><td>' + \
        '</td></tr><tr><td>'.join(['{0}</td><td>{1}</td><td>{2}'.format(v, type(eval(v)).__name__, str(eval(v))) for v in values]) + \
        '</td></tr></table>'

def _ipython_display_(self):
    """Called when display() or pyout is used to display the Variable 
    Inspector."""
    self._box._ipython_display_()

运行 与以下内联:

inspector = VariableInspectorWindow(get_ipython())
inspector

使其成为 javascript 弹出窗口;

%%javascript
$('div.inspector')
    .detach()
    .prependTo($('body'))
    .css({
        'z-index': 999, 
        position: 'fixed',
        'box-shadow': '5px 5px 12px -3px black',
        opacity: 0.9
    })
    .draggable();

更新

日期:2017 年 5 月 17 日

@jfbercher created a nbextension variable inspector. The source code can be seen here jupyter_contrib_nbextensions. For more information see the docs.

安装

用户

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user

虚拟环境

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --sys-prefix

启用

jupyter nbextension enable varInspector/main

这是一个屏幕截图;

如果您在 Jupyter Lab there has been a lot of discussion about implementing a variable explorer/inspector. You can follow the issue here

内使用 Jupyter 笔记本

截至目前,有一个 Jupyter Lab 扩展正在开发中,它实现了一个类似 Spyder 的变量浏览器。它基于詹姆斯在他的回答中提到的笔记本扩展。您可以在此处找到实验室扩展(带有安装说明):https://github.com/lckr/jupyterlab-variableInspector

如果您正在使用 Visual Studio 代码,它已经存在:

另一个解决方案是将 spyder-console 连接到 运行ning 内核

在任何平台上都是:

  1. 在 jupyter 中:运行 以下 ():
from jupyter_client import find_connection_file
print(find_connection_file()) #this will show which json-file is associated to your jupyter

它应该给你这样的东西:~/.local/share/jupyter/runtime/kernel-<SOME-ID>.json'

  1. 在您的 spyder 控制台中,右键单击并 select“连接到现有内核”,浏览到您之前找到的那个文件。
    • 勾选“保存连接设置”,方便下次查找
    • 取消勾选“这是一个远程内核(通过 SSH)”(除非您知道自己在做什么)
  2. 然后您可以使用 jupyter 实例中的 spyder 浏览变量

这种方法的好处是您不需要安装附加包,您只需要 spyder 和 jupyter。

编辑:我太乐观了,但似乎spyder also has a problem,我可以使用控制台中的变量,但它没有显示变量实际 GUI/browser。我留下了答案,希望将来能解决这个问题。 (它也可能会起作用,具体取决于您安装的版本)。也许一个解决方案是将 jupyter 连接到现有内核,但我无法使其工作。欢迎任何帮助!

为了利用已接受的答案,在 VE 中安装的最佳方法是 运行 以下内容:

import sys
!{sys.executable} -m pip install jupyter_contrib_nbextensions