Ari*_*ide 5 python ipython ipython-magic jupyter-notebook
line-magic命令%load将给定文件的内容加载到当前单元格中,例如,执行:
[cell 1] %load hello_world.py
Run Code Online (Sandbox Code Playgroud)
...将单元格转换为:
[cell 1] # %load hello_world.py
print("hello, world")
Run Code Online (Sandbox Code Playgroud)
我想创建一个%load_nextline-magic 命令,它将将此文件加载到下一个单元格中。例如,在以下笔记本中执行单元 1:
[cell 1] %load_next hello_world.py
[cell 2] print("hello, cruel world") # original content
Run Code Online (Sandbox Code Playgroud)
...将保持单元格 1 不变并使用新内容更新单元格 2:
[cell 1] %load_next hello_world.py
[cell 2] print("hello, world")
Run Code Online (Sandbox Code Playgroud)
我已经尝试过这个:
[cell 1] %load hello_world.py
Run Code Online (Sandbox Code Playgroud)
但它会在当前单元格和下一个单元格之间插入内容:
[cell 1] %load_next hello_world.py
[cell 2] print("hello, world")
[cell 3] print("hello, cruel world") # original content
Run Code Online (Sandbox Code Playgroud)
是否可以使其替换下一个单元格,或在插入下一个单元格之前删除下一个单元格?
您可以运行下面的脚本。无法获取所有单元格,因此我决定运行javascript代码来删除下一个单元格。Js部分查找所有单元格并从当前单元格中删除下一个单元格。我已经在Jupyter Notebook和上进行了测试Jupyter Lab。
from IPython.display import display, HTML, Javascript
from IPython.core.magic import Magics, magics_class, line_magic
from pathlib import Path
@magics_class
class MyMagics(Magics):
@line_magic
def load_next(self, line):
js_script = r"""<script>
if (document.getElementById('notebook-container')) {
//console.log('Jupyter Notebook');
allCells = document.getElementById('notebook-container').children;
selectionClass = /\bselected\b/;
jupyter = 'notebook';
}
else if (document.getElementsByClassName('jp-Notebook-cell').length){
//console.log('Jupyter Lab');
allCells = document.getElementsByClassName('jp-Notebook-cell');
selectionClass = /\bjp-mod-selected\b/;
jupyter = 'lab';
}
else {
console.log('Unknown Environment');
}
if (typeof allCells !== 'undefined') {
for (i = 0; i < allCells.length - 1; i++) {
if(selectionClass.test(allCells[i].getAttribute('class'))){
allCells[i + 1].remove();
// remove output indicators of current cell
window.setTimeout(function(){
if(jupyter === 'lab') {
allCells[i].setAttribute('class', allCells[i].getAttribute('class') + ' jp-mod-noOutputs');
allCells[i].getElementsByClassName('jp-OutputArea jp-Cell-outputArea')[0].innerHTML = '';
} else if(jupyter === 'notebook'){
allCells[i].getElementsByClassName('output')[0].innerHTML = '';
}
}, 20);
break;
}
}
}
</script>"""
# remove next cell
display(HTML(js_script))
new_content = Path(line).read_text()
self.shell.set_next_input(new_content, replace=False)
ip = get_ipython()
ip.register_magics(MyMagics)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
751 次 |
| 最近记录: |