如何检查是否启用了 Jupyter Notebook 扩展?

Mac*_*ala 5 python matplotlib jupyter jupyter-notebook ipywidgets

我想以编程方式从 Jupyter Notebook检查是否启用了 ipywidgets 。有哪些方法可以做到?我尝试查看nbextensionsnotebook模块,但没有找到列出已启用扩展的功能。

我的笔记本在 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();
Run Code Online (Sandbox Code Playgroud)

在伪代码中,我想实现这样的目标:

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

从命令行,概念上类似的命令是jupyter nbextension list,但我想从正在运行的 Python 环境中执行此操作,还可以在用户仅查看 GitHub 上的 Notebook(或类似)时提供静态绘图。

谢谢 :)

Imp*_*est 3

我可能会误解这里到底要求什么;但是,我觉得通常的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()
Run Code Online (Sandbox Code Playgroud)