问题描述
在 jupyter 中有一个神奇的函数可以捕获和解析单元格的输出:
%%capture capt_out
# cell body that prints interesting stuff every second
# another cell
# code for printing or processing output (i.e for plots):
print(capt_out)
问题是,我需要实时查看输出(因为这是一个暗网模型训练,我需要知道取得了多少进展),然后对其进行解析以创建基于它的图。
解决方法
这不是通用的解决方案,但适用于我的情况:
!./darknet detector some_parameters 2>&1 | tee some_file.txt
由于我的 jupyter 单元通过 bash 运行二进制文件,因此我可以简单地使用 tee
命令将输出保存到文件,而不会抑制实时打印。然后我用python读取这个文件
with open(some_file.txt,r) as f:
text = f.read()
2>&1
将 stderr 重定向到 stdout。