2017-08-12 71 views
1

我想以编程方式从Jupyter笔记本检查ipywidgets是否启用。有什么方法可以这样做?我试图查看nbextensionsnotebook模块,但没有找到列出启用的扩展的功能。如何检查Jupyter Notebook扩展是否已启用?

我的笔记本在GitHub上,我想在那里提供一个静态图,另外还有一个交互式版本,如果用户实际上正在运行笔记本并安装了ipywidgets并且已启用。

的绘制代码

# Setup by importing some libraries and configuring a few things 
import numpy as np 
import ipywidgets 
import matplotlib.pyplot as plt 
%matplotlib inline 

# Create two random datasets 
data = np.random.random(15) 
smallerdata = np.random.random(15) * 0.3 

# Define a plotting function 
def drawPlot(): 
    plt.plot(range(len(data)), data, label="random data"); 
    plt.plot(range(len(smallerdata)), smallerdata, 'r--', label="smaller random data"); 
    plt.title("Two random dataset compared"); 
    plt.grid(axis='y'); 
    plt.legend(); 

# Define an interactive annotation function 
def updatePlot(s=0): 
    print("data {0:.2f}, smallerdata {1:.2f}".format(data[s], smallerdata[s])) 
    drawPlot() 
    plt.annotate(s=round(data[s], 2), 
       xy=(s, data[s]), 
       xytext=(s + 2, 0.5), 
       arrowprops={'arrowstyle': '->'}); 
    plt.annotate(s=round(smallerdata[s], 2), 
       xy=(s, smallerdata[s]), 
       xytext=(s + 2, 0.3), 
       arrowprops={'arrowstyle': '->'}); 
    plt.show(); 

伪代码,我想实现这样的事情:

if nbextensions.enabled('ipywidgets'): 
    slider = ipywidgets.interactive(updatePlot, s=(0, len(data) - 1, 1)); 
    display(slider) 
else: 
    drawPlot() 

在命令行中,在概念上类似的命令是jupyter nbextension list,但我想这样做这来自正在运行的Python环境,当用户只是在GitHub(或类似的)上查看Notebook时,也会提供一个静态图。

谢谢:)

+0

在任何情况下显示该情节,只要显示小部件,如果可能的话呢? – ImportanceOfBeingErnest

+0

感谢@ImportanceOfBeingErnest,从概念上讲,这正是我的想法。但是,由于我正在从小部件重绘图,如果启用了ipywidgets,会导致绘制两个副本:首先是静态的,然后是交互式的。这是我现在的情况:) –

回答

1

我可能误解究竟是什么在这里要求;不过,我觉得像通常的try - except解决方案将工作。

import numpy as np 
import matplotlib.pyplot as plt 
%matplotlib inline 

data = np.random.random(15) 
smallerdata = np.random.random(15) * 0.3 

def drawPlot(): 
    plt.plot(range(len(data)), data, label="random data"); 
    plt.plot(range(len(smallerdata)), smallerdata, 'r--', label="smaller random data"); 
    plt.title("Two random dataset compared"); 
    plt.grid(axis='y'); 
    plt.legend(); 

def updatePlot(s=0): 
    print("data {0:.2f}, smallerdata {1:.2f}".format(data[s], smallerdata[s])) 
    drawPlot() 
    plt.annotate(s=round(data[s], 2), 
       xy=(s, data[s]), 
       xytext=(s + 2, 0.5), 
       arrowprops={'arrowstyle': '->'}); 
    plt.annotate(s=round(smallerdata[s], 2), 
       xy=(s, smallerdata[s]), 
       xytext=(s + 2, 0.3), 
       arrowprops={'arrowstyle': '->'}); 
    plt.show(); 

try: 
    import ipywidgets 
    from IPython.display import display 
    slider = ipywidgets.interactive(updatePlot, s=(0, len(data) - 1, 1)); 
    display(slider) 
except: 
    drawPlot()