Nice programing

Jupyter 노트북의 변수 탐색기

nicepro 2020. 12. 11. 19:26
반응형

Jupyter 노트북의 변수 탐색기


Spyder와 같이 Jupyter (IPython)에 변수 탐색기가 있습니까? 테스트 코드를 실행할 때마다 항상 변수 목록을 인쇄해야하는 것은 매우 불편합니다.

이 기능이 아직 구현 되었습니까? 그렇다면 어떻게 활성화합니까?


최신 정보

훨씬 덜 복잡한 방법을 보려면 업데이트라는 섹션으로 스크롤하십시오.

오래된 답변

다음은 자신 만의 Variable Inspector 를 만드는 방법에 대한 노트북입니다 . 나는 jupyter 노트북이 ipython 노트북이라고 불렸을 때 다시 작성되었다고 생각하지만 최신 버전에서 작동합니다.

링크가 끊어지는 경우를 대비하여 아래 코드를 게시하겠습니다.

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
$('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 가 nbextension 변수 검사기를 만들었습니다. 소스 코드는 여기 jupyter_contrib_nbextensions에서 볼 수 있습니다 . 자세한 내용은 문서를 참조하십시오 .

설치

사용자

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

다음은 스크린 샷입니다.

enter image description here


이것은 Spyder가 제공하는 것이 아니라 훨씬 간단하지만 도움이 될 수 있습니다.

현재 정의 된 모든 변수 목록을 가져 오려면 who를 실행하십시오 .

In [1]: foo = 'bar'

In [2]: who
foo

자세한 내용을 보려면 whos를 실행하십시오 .

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

내장 함수의 전체 목록은 Magic Commands를 참조하십시오.


Jupyter Lab 에서 Jupyter Notebook을 사용 하는 경우 변수 탐색기 / 검사기 구현에 대해 많은 논의가있었습니다. 여기 에서 문제를 따를 수 있습니다.

As of right now there is one Jupyter Lab extension in the works that implements a Spyder-like variable explorer. It is based on the notebook extension that James mentioned in his answer. You can find the lab extension (with installation instructions) here: https://github.com/lckr/jupyterlab-variableInspector

enter image description here

참고URL : https://stackoverflow.com/questions/37718907/variable-explorer-in-jupyter-notebook

반응형