gpt4 book ai didi

python - 定义一个 IPython 魔法来替换下一个单元格的内容

转载 作者:行者123 更新时间:2023-12-04 13:30:30 24 4
gpt4 key购买 nike

%load line-magic 命令将给定文件的内容加载到 当前 单元格,例如,执行:

[cell 1]    %load hello_world.py
...将单元格转换为:
[cell 1]    # %load hello_world.py
print("hello, world")
我想创建一个 %load_next line-magic 命令会将该文件加载到 下一个 细胞。例如,在以下笔记本中执行单元格 1:
[cell 1]    %load_next hello_world.py

[cell 2] print("hello, cruel world") # original content
... 将保持单元格 1 不变并使用新内容更新单元格 2:
[cell 1]    %load_next hello_world.py

[cell 2] print("hello, world")
我试过这个:
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):
new_content = Path(line).read_text()
self.shell.set_next_input(new_content, replace=False)

ip = get_ipython()
ip.register_magics(MyMagics)
但它 Blade 当前单元格和下一个单元格之间的内容:
[cell 1]    %load_next hello_world.py

[cell 2] print("hello, world")

[cell 3] print("hello, cruel world") # original content
是否可以在插入之前替换下一个单元格或删除下一个单元格?

最佳答案

您可以运行以下脚本。没有办法获取所有单元格,所以我决定运行 javascript删除下一个单元格的代码。 Js part 查找所有单元格并从当前单元格中删除下一个单元格。我已经在 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)

关于python - 定义一个 IPython 魔法来替换下一个单元格的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65379879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com