在运行期间选择在ipython笔记本中运行哪些单元格的简单方法

Nat*_*oyd 6 ipython ipython-notebook

我有一个ipython笔记本,它在数据处理程序中运行几个步骤,并在整个过程中将信息保存在文件中.这样,在开发我的代码时(主要是在一个单独的.py模块中),我可以跳过并运行各种步骤.我想设置它以便我可以Cell- > run all但只让它执行某些易于选择的选定步骤.例如,我想要定义我想在dict中运行的步骤,如下所示:

process = {
    'load files':False,
    'generate interactions list':False,
    'random walk':True,
    'dereference walk':True,
    'reduce walk':True,
    'generate output':True
}
Run Code Online (Sandbox Code Playgroud)

然后步骤将基于此dict运行.顺便说一下,每个步骤包括多个细胞.

我认为%macro不是我想要的,因为任何时候我改变任何东西或重新启动内核我都必须重新定义宏,改变单元格数.

那些线上是否有像魔术%skip%skipto魔法一样的东西?或者也许是一种干净的方式放在细胞的开头,if process[<current step>]: %dont_run_rest_of_cell

Rob*_*bbe 9

您可以借助自定义内核扩展创建自己的跳过魔法.

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']
Run Code Online (Sandbox Code Playgroud)

在笔记本中加载扩展程序:

%load_ext skip_kernel_extension
Run Code Online (Sandbox Code Playgroud)

在要跳过的单元格中运行skip magic命令:

%%skip True  #skips cell
%%skip False #won't skip
Run Code Online (Sandbox Code Playgroud)

您可以使用变量来决定是否应使用$跳过单元格:

should_skip = True
%%skip $should_skip
Run Code Online (Sandbox Code Playgroud)


Gor*_*ean 8

如果您使用 nbconvert 来执行您的笔记本,您可以编写一个自定义预处理器,查看单元格元数据以了解要执行的单元格。

class MyExecutePreprocessor(nbconvert.preprocessors.ExecutePreprocessor):

    def preprocess_cell(self, cell, resources, cell_index):
        """
        Executes a single code cell. See base.py for details.
        To execute all cells see :meth:`preprocess`.

        Checks cell.metadata for 'execute' key. If set, and maps to False, 
          the cell is not executed.
        """

        if not cell.metadata.get('execute', True):
            # Don't execute this cell in output
            return cell, resources

        return super().preprocess_cell(cell, resources, cell_index)
Run Code Online (Sandbox Code Playgroud)

通过编辑单元格元数据,您可以指定是否应执行该单元格。

您可以通过将主词典添加到您的笔记本元数据来变得更有趣。这看起来像您示例中的字典,将部分映射到布尔值,指定是否调用该部分。

然后,在您的单元元数据中,您可以使用映射到笔记本元数据中的部分 ID 的“部分”关键字。

执行 nbconvert 时,您可以告诉它使用您的预处理器。

有关更多信息,请参阅Notebook 预处理器上的文档


Ruf*_*sVS 5

我是 Jupyter Notebook 的新手,并且很喜欢它。我以前听说过 IPython,但直到最近的一份咨询工作才认真研究它。

我的同事向我展示了禁用块执行的一个技巧,即将它们从“代码”类型更改为“原始 NBConvert”类型。通过这种方式,我可以在笔记本上撒上诊断块,但只有在我希望它们运行时才打开它们(使它们成为“代码”)。

此方法在脚本中不能完全动态选择,但可能适合某些需求。


use*_*916 0

明确的总是比隐含的更好。简单总比复杂好。那么为什么不使用普通的 python 呢?

每一步使用一个单元格,您可以执行以下操作:

if process['load files']:
    load_files()
    do_something()
Run Code Online (Sandbox Code Playgroud)

if process['generate interactions list']:
    do_something_else()
Run Code Online (Sandbox Code Playgroud)

如果您想在跳过特定步骤时停止执行,可以使用:

if not process['reduce walk']:
    stop
else:
    reduce_walk()
    ...
Run Code Online (Sandbox Code Playgroud)

stop不是命令,因此在使用Cell -> Run all时会生成异常并停止执行。

您还可以执行条件步骤,例如:

if process['reduce walk'] and process['save output']:
    save_results()
    ...
Run Code Online (Sandbox Code Playgroud)

但是,根据经验,我不会设定比这复杂得多的条件。