본문 바로가기

개발하자

주피터 노트북의 가변 탐색기

반응형

주피터 노트북의 가변 탐색기

스파이더처럼 목성(IPython)에도 가변 탐험가가 있나요? 테스트 코드를 실행할 때마다 변수 목록을 항상 인쇄해야 하는 것은 매우 불편합니다.

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




이것은 Spyder가 제공하는 것이 정확하지 않고 훨씬 단순하지만 도움이 될 수 있습니다.

현재 정의된 모든 변수의 목록을 가져오려면 다음을 실행합니다.

In [1]: foo = 'bar'

In [2]: who
foo

자세한 내용은 다음을 실행하십시오.

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

기본 제공 기능의 전체 목록은 다음을 참조하십시오.




갱신하다

훨씬 덜 복잡한 방법을 위해 update 섹션으로 스크롤합니다.

오래된 답

여기 직접 만드는 방법에 대한 공책이 있습니다. 주피터 공책을 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일

확장 변수 검사기를 만들었습니다. 소스 코드는 여기에서 확인할 수 있습니다. 자세한 내용은 를 참조하십시오.

설치하다

사용자

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




내에서 Jupyter 노트북을 사용하는 경우 변수 탐색기/인스펙터를 구현하는 것에 대해 많은 논의가 있었습니다. 당신은 이슈를 따라갈 수 있다.

현재로서는 스파이더와 같은 변수 탐사기를 구현하는 주피터 랩의 확장이 하나 있다. 제임스가 답변에서 언급한 노트북 확장자를 기반으로 합니다. 설치 지침과 함께 연구소 확장을 찾을 수 있습니다.

enter image description here




Visual Studio Code를 사용하는 경우 이미 다음과 같이 표시됩니다.

enter image description here




또 다른 해결책은 스파이더 콘솔을 실행 중인 커널에 연결하는 것이다.

어떤 플랫폼에서든 다음과 같습니다.

  1. 주피터에서: 다음을 실행한다().
from jupyter_client import find_connection_file
print(find_connection_file()) #this will show which json-file is associated to your jupyter

다음과 같은 것을 제공해야 합니다.

  1. 스파이더 콘솔에서 마우스 오른쪽 단추를 클릭하고 " "를 선택하여 이전에 찾은 파일을 찾습니다.
  2. 그런 다음 주피터 인스턴스에 있는 스파이더를 사용하여 변수를 탐색할 수 있습니다.

이 방법의 장점은 추가 패키지를 설치할 필요가 없고 스파이더와 주피터만 있으면 된다는 것이다.

너무 낙관적이었는데, 콘솔의 변수를 사용할 수는 있지만 실제 GUI/브라우저에서는 변수가 표시되지 않는 것 같습니다. 앞으로 이 문제가 해결되길 바라며 답을 남깁니다. 설치한 버전에 따라 작동할 수도 있습니다. 아마도 해결책은 기존 커널에 주피터를 연결하는 것일 수도 있지만, 나는 그것을 작동시킬 수 없었다. 어떤 도움이라도 환영합니다!




승인된 답변을 피기백하기 위해 VE에 설치하는 가장 좋은 방법은 다음을 실행하는 것입니다.

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

반응형