在运行期间选择在ipython notebook中运行哪些单元格的简单方法 [英] Simple way to choose which cells to run in ipython notebook during run all
问题描述
我有一个ipython笔记本,它在数据处理程序中运行几个步骤,并在整个过程中将信息保存在文件中。这样,在开发我的代码时(主要是在一个单独的.py模块中),我可以跳过并运行各种步骤。我想设置它以便我可以 Cell
- > 运行所有
但只执行某些选择容易选择的步骤。例如,我想要定义我想在dict中运行的步骤,如下所示:
I have an ipython notebook that runs several steps in a data processing routine and saves information in files along the way. This way, while developing my code (mostly in a separate .py module), I can skip to and run various steps. I'd like to set it up so that I can Cell
->run all
but only have it execute certain chosen steps that would be easily chosen. e.g., I'd envision defining the steps I want to run in a dict like so:
process = {
'load files':False,
'generate interactions list':False,
'random walk':True,
'dereference walk':True,
'reduce walk':True,
'generate output':True
}
然后步骤将根据这个字典运行。顺便说一句,每一步都包含多个单元格。
then the steps would run based on this dict. BTW, each step comprises multiple cells.
我认为%macro
不是我想要的,因为我随时改变了任何事情或重新启动内核我必须重新定义宏,更改单元格数。
I think %macro
is not quite what I want since anytime I changed anything or restarted the kernel I'd have to redefine the macro, with changing cell numbers.
是否有像%skip
或%skipto
魔法或其他类似的东西?或者可能是一个干净的方式放在单元格的开头,如果进程[<当前步骤>]:%dont_run_rest_of_cell
?
Is there like a %skip
or %skipto
magic or something along those lines? Or perhaps a clean way to put at the beginning of cells, if process[<current step>]: %dont_run_rest_of_cell
?
推荐答案
您可以借助自定义内核扩展创建自己的跳过魔法。
You can create your own skip magic with the help of a custom kernel extension.
skip_kernel_extension。 py
def skip(line, cell=None):
'''Skips execution of the current line/cell if line evaluates to True.'''
if eval(line):
return
get_ipython().ex(cell)
def load_ipython_extension(shell):
'''Registers the skip magic when the extension loads.'''
shell.register_magic_function(skip, 'line_cell')
def unload_ipython_extension(shell):
'''Unregisters the skip magic when the extension unloads.'''
del shell.magics_manager.magics['cell']['skip']
在笔记本中加载扩展程序:
Load the extension in your notebook:
%load_ext skip_kernel_extension
在要跳过的单元格中运行skip magic命令:
Run the skip magic command in the cells you want to skip:
%%skip True #skips cell
%%skip False #won't skip
您可以使用变量来决定如果应该使用$跳过单元格:
You can use a variable to decide if a cell should be skipped by using $:
should_skip = True
%%skip $should_skip
这篇关于在运行期间选择在ipython notebook中运行哪些单元格的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!