如何在IPython Shell中满足条件时阻止单元格执行?
问题描述
在IPython交互式Shell中运行以下代码注册pre_run_cell钩子:
def pre_run_cell(info): raise RuntimeError("please don't run") get_ipython().events.register("pre_run_cell", pre_run_cell)
此时每次运行单元格前会触发pre_run_cell(),但即便该函数抛出错误,单元格仍会被执行,示例输出如下:
In [3]: 1 Error in callback <function pre_run_cell at 0x7f6eae1a6020> (for pre_run_cell), with arguments args (<ExecutionInfo object at 7f6eae4346d0, raw_cell="1" store_history=True silent=False shell_futures=True cell_id=None>,),kwargs {}: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[1], line 2, in pre_run_cell(info) 1 def pre_run_cell(info): ----> 2 raise RuntimeError("please don't run") RuntimeError: please don't run Out[3]: 1
需求:在每次运行单元格前(或pre_run_cell钩子内)检查特定条件,满足条件时阻止单元格运行。
解决方案
可以通过修改pre_run_cell钩子接收的ExecutionInfo对象的skip_execution属性来阻止单元格执行,无需抛出错误。具体实现如下:
def pre_run_cell(info): # 替换为你的特定检查逻辑 should_block = True if should_block: info.skip_execution = True print("单元格已被阻止执行") get_ipython().events.register("pre_run_cell", pre_run_cell)
当条件满足时,设置info.skip_execution = True会让IPython跳过当前单元格的执行流程,同时可以自定义提示信息。
如果需要在阻止执行的同时抛出错误提示,也可以结合设置属性和异常抛出,此时单元格同样不会执行:
def pre_run_cell(info): should_block = True if should_block: info.skip_execution = True raise RuntimeError("满足条件,阻止单元格运行") get_ipython().events.register("pre_run_cell", pre_run_cell)
内容的提问来源于stack exchange,提问作者user202729
相关产品推荐
相关产品推荐

