在运行所有期间选择在 ipython notebook 中运行哪些单元的简单方法 [英] Simple way to choose which cells to run in ipython notebook during run all
问题描述
我有一个 ipython 笔记本,它在数据处理例程中运行多个步骤,并在此过程中将信息保存在文件中.这样,在开发我的代码时(主要是在一个单独的 .py 模块中),我可以跳到并运行各个步骤.我想设置它以便我可以 Cell
->run all
但只让它执行某些可以轻松选择的选定步骤.例如,我想像这样定义我想在 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
}
然后这些步骤将根据这个 dict 运行.顺便说一句,每个步骤都包含多个单元格.
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
的魔法或类似的东西?或者也许是一种放在单元格开头的干净方法,if process[
?
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
在要跳过的单元格中运行跳过魔术命令:
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屋!