如何将单元格输出打印到 colab 上的文件

How to print cell output to a file on colab

在 Google Colab 中,我想执行几行 python 代码,包括打印和函数。目标是重定向结果到文件。有什么提示吗?

  1. In the cell do you want to print to the file write the following:
%%capture cap
  1. For print into a file:
f = open("output.txt", "w") 
print(cap, file=f)
f.close()
  • 注意:对于非常大的输出,它可能无法很好地工作。 变量 c 的对象类型是 CapturedIO from IPython.utils.capture