是否有IPython行魔法命令可捕获单行代码的输出?
最优解决方案
不需要将目标代码移到单独单元格,有两种成熟的实现方式:
方案1:Python原生上下文管理器(推荐,兼容性最好)
用contextlib.redirect_stdout仅包裹需要捕获输出的代码行,其他代码的输出不受影响,完全符合需求。
你的示例代码可以修改为:
import h2o from contextlib import redirect_stdout import io h2o.init() train_fr = h2o.H2OFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}) test_fr = h2o.H2OFrame({'a': [4], 'b': [7], 'c': [10]}) drf = h2o.estimators.H2ORandomForestEstimator() drf.train(y = 'c', training_frame = train_fr) # 仅捕获模型评估打印的输出 output_buffer = io.StringIO() with redirect_stdout(output_buffer): print(drf.model_performance(test_data = test_fr)) performance_output = output_buffer.getvalue() h2o.shutdown()
之后写入文件直接使用捕获的变量即可:
with open('model_performance.txt', mode = 'w') as file: file.write(performance_output)
这样写入的内容就完全是你期望的模型评估结果,不会包含其他代码的日志输出。
方案2:IPython行魔法命令
IPython的%capture不仅有单元格模式%%capture,也支持行模式,仅捕获单行语句的输出:
%capture performance_output print(drf.model_performance(test_data = test_fr))
捕获的输出保存在performance_output.stdout属性中,直接写入文件即可。
补充说明
- 如果你需要同时捕获stderr输出,可以搭配
contextlib.redirect_stderr使用,行魔法%capture默认会同时捕获stdout和stderr,无需额外配置。 - 两种方案都不需要拆分单元格,也不会影响其他代码的正常运行和输出。
内容的提问来源于stack exchange,提问作者user13867283
相关产品推荐
相关产品推荐

