前言:
在用python编程的时候,你是否偶尔有个需求?需要把输出的日志 or 信息清空?以下笔者将从3个角度讨论清空输出的简单方式
1. Jupyter notebook下的输出清空
主要通过IPython.display.clear_output来清空
from IPython.display import clear_output as clear
print('before')
clear() # 清除输出
print('after')
具体案例

2. Terminal/Console下的输出清空
使用os.system('cls')或os.system('clear')来清空
import os
print('before')
os.system('cls' if os.name == 'nt' else 'clear')
print('after')
3. 综合
import os, sys
def clear_output():
os.system('cls' if os.name == 'nt' else 'clear')
if 'ipykernel' in sys.modules:
from IPython.display import clear_output as clear
clear()
print('before')
clear_output() # 清除输出
print('after')

本文介绍了三种在Python环境中清空输出的方式:1. 在Jupyter Notebook中使用`IPython.display.clear_output`;2. 在命令行终端使用`os.system('cls' if os.name=='nt' else 'clear')`;3. 结合以上两种方式实现跨环境的输出清空。
2329

被折叠的 条评论
为什么被折叠?



