Python 3.x 对Jupyter笔记本电池的输出进行测试
我正在使用Jupyter笔记本或Jupyter实验室教授Python的基础知识 是否可以在不抑制单元格输出的情况下对前一个单元格的标准输出运行测试 MagicsPython 3.x 对Jupyter笔记本电池的输出进行测试,python-3.x,jupyter-notebook,jupyter-lab,Python 3.x,Jupyter Notebook,Jupyter Lab,我正在使用Jupyter笔记本或Jupyter实验室教授Python的基础知识 是否可以在不抑制单元格输出的情况下对前一个单元格的标准输出运行测试 Magics%%capture使用标准配置重定向标准输出。我希望在运行测试之前仍然能够看到单元格的输出 e、 g 测试单元: [cell 2] >> if (cell1.stdout == 'Hello, world!'): ... print('Success!') ... else:
%%capture
使用标准配置重定向标准输出。我希望在运行测试之前仍然能够看到单元格的输出
e、 g
测试单元:
[cell 2] >> if (cell1.stdout == 'Hello, world!'):
... print('Success!')
... else:
... print('Tests failed')
这非常简单,只需将
%%capture
魔术包装成一个自定义函数,显示捕获的输出:
from IPython.core import magic
@magic.register_cell_magic
def non_suppressing_capture(variable, cell):
get_ipython().magics_manager.magics['cell']['capture'](variable, cell)
globals()[variable].show()
并且(在执行上述代码后)按如下方式使用:
%%non_suppressing_capture cell1
print('Hello, world!')
实际上,除非在测试字符串中添加新行字符,否则测试将失败:
if cell1.stdout == 'Hello, world!\n':
print('Success!')
else:
print('Tests failed')
伊皮顿魔术是一个强大的工具。您可以在文档中找到更多高级示例,请参阅:章节和API文档:
if cell1.stdout == 'Hello, world!\n':
print('Success!')
else:
print('Tests failed')