我想定期清除 Google Colab 中某个单元的输出,该单元使用
!python file.py
运行本地 python 文件
我已经在 stackoverflow 上尝试过这个问题的答案:
from google.colab import output
output.clear()
和
from IPython.display import clear_output
clear_output()
如果我直接在单元格中运行它们而不是通过本地文件运行它们,那么这两个都可以工作。
from IPython.display import clear_output
clear_output()
这在 Google Colab 中对我有用:
我在以下位置找到了此代码:
https://www.codegrepper.com/code-examples/python/jupyter+clear+cell+output+programmatically
from IPython.display import clear_output
# your code here...
clear_output()
而不是跑步
!python file.py
你可以用这个。
%run file.py
它会按预期工作。
IPython 主要用于 Jupyter,如果正确实现,它应该可以在 Colab 中用于本地文件。不要忘记在主 python 代码中导入库。
扩展 korakot 的答案,在“file.py”中尝试这个
```
from IPython.display import clear_output
from time import sleep
for i in range(3):
for j in range(10):
print('Hello World')
sleep(3)
clear_output()
```
然后
%run file.py
在 Colab 单元中。