python - 如何在 Python Jupyter Notebook 的按钮中编写“重新启动内核并运行所有”代码?
问题描述
我正在尝试使用 python 在 Jupyter notebook 中创建一个 GUI。我已经编写了按钮以使用小部件执行代码。但是我遇到了两个问题:
- 编写代码片段以重新启动内核并运行所有单元(下面代码片段中的 rs_button)
- 不太重要:无论如何我可以隐藏python中的所有代码,只保留按钮以及用户输入单元格显示?
这是我一直在尝试的:
import ipywidgets as widgets
from IPython.display import display
rs_button = widgets.Button(description="Restart Kernel!")
exec_button = widgets.Button(description="Click Me!")
display(rs_button,exec_button)
def rs_button_clicked(b):
IPython.notebook.execute_cell();
def exec_button_clicked(b):
import data_assess_v6 as data_profiler
(execution_time) = data_profiler.data_profile(path,file)
rs_button.on_click(rs_button_clicked)
exec_button.on_click(exec_button_clicked)
谢谢
解决方案
我已经能够通过将javascript注入笔记本来实现这两个功能。下面是代码片段。
from IPython.display import HTML, Javascript, display
def initialize():
display(HTML(
'''
<script>
code_show = false;
function restart_run_all(){
IPython.notebook.kernel.restart();
setTimeout(function(){
IPython.notebook.execute_all_cells();
}, 10000)
}
function code_toggle() {
if (code_show) {
$('div.input').hide(200);
} else {
$('div.input').show(200);
}
code_show = !code_show
}
</script>
<button onclick="code_toggle()">Click to toggle</button>
<button onclick="restart_run_all()">Click to Restart and Run all Cells</button>
'''
))
initialize()
该restart_run_all()
函数重新启动笔记本内核,然后在 10 秒后执行所有单元。可以根据需要调整超时功能的参数。
该code_toggle()
函数切换笔记本中单元格的输入区域。它还在切换代码单元时提供了一个很好的动画。
推荐阅读
- firebase - 如何阻止某些 IP 地址访问您在 Firebase 托管上的网站
- c - 我无法在我的 Windows 桌面上编译 GMP 库(用于 c 或 c++)
- dataframe - 如何使来自 for 循环的数组在 Julia 中全局可用?
- python - 训练准确度分数不同于后续测试准确度分数
- r - 如何表示组中的两个最高观察值(有两个条件)?
- r - confint() 是否以对数赔率或赔率返回 CI?
- wordpress - 用另一个替换 WordPress 主题的搜索栏
- python - 如何获取用户输入并将其替换为求解方法?
- sql - 逗号分隔字段上的表值函数 (TVF)
- laravel - 使用 Vue Js 下载文本文件