欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何:从Jupyter / IPython笔记本中挽救丢失的代码

程序员文章站 2022-04-21 12:02:26
...

Jupyter (formerly known as IPython) notebooks are great – but have you ever accidentally deleted a cell that contained a really important function that you want to keep? Well, this post might help you get it back.

Jupyter(以前称为IPython)笔记本非常棒-但是您是否偶然删除了包含要保留的非常重要功能的单元格? 好吧,这篇文章可能会帮助您找回。

So, imagine you have a notebook with the following code:

因此,假设您有一个带有以下代码的笔记本:

如何:从Jupyter / IPython笔记本中挽救丢失的代码 and then you accidentally delete the top cell, with the definition of your function…oops! Furthermore, you can’t find it in any of your ‘Checkpoints’ (look under the File menu). Luckily, your function is still defined…so you can still run it:

然后您不小心删除了具有功能定义的顶部单元格……糟糕! 此外,您无法在任何“检查点”中找到它(在“文件”菜单下查看)。 幸运的是,您的函数仍处于定义状态,因此您仍然可以运行它:

如何:从Jupyter / IPython笔记本中挽救丢失的代码

This is essential for what follows…because as the function is still defined, the Python interpreter still knows internally what the code is, and it gives us a way to get this out!

这对于接下来的工作非常重要……因为该函数仍处于定义状态,Python解释器仍内部知道代码是什么,并且它为我们提供了一种实现方法!

So, if you’re stuck and just want the way to fix it, then here it is:

因此,如果您卡住了,只想修复它,那么这里是:

def rescue_code(function):
    import inspect
    get_ipython().set_next_input("".join(inspect.getsourcelines(function)[0]))

Just call this as rescue_code(f), or whatever your function is, and a new cell should be created with the code of you function: problem solved! If you want to learn how it works then read on…

只需将其称为result_code(f)或任何函数即可,然后应使用函数代码创建一个新单元格:问题已解决! 如果您想了解其工作原理,请继续阅读...

如何:从Jupyter / IPython笔记本中挽救丢失的代码

The code is actually very simple, inspect.getsourcelines(function) returns a tuple containing a list of lines of code for the function and the line of the source file that the code starts on (as we’re operating in a notebook this is always 1). We extract the 0th element of this tuple, then join the lines of code into one big string (the lines already have n at the end of them, so we don’t have to deal with that. The only other bit is a bit of IPython magic to create a new cell below the current cell and set it’s contents….and that’s it!

该代码实际上非常简单, inspect.getsourcelines(function)返回一个元组,其中包含该function的代码行列表以及该代码开始的源文件行(因为我们在笔记本中进行操作,因此始终1)。 我们提取该元组的第0个元素,然后将代码行连接到一个大字符串中(这些行的末尾已经有n ,因此我们不必对此进行处理。唯一的一点是IPython的魔力是在当前单元格下方创建一个新的单元格并设置其内容...就这样!

翻译自: https://www.pybloggers.com/2016/04/how-to-rescue-lost-code-from-a-jupyteripython-notebook/