The output of python in jupyter notebook/terminal/console is cleared

Foreword:

When programming in python, do you occasionally have a need? Need to clear the output log or information? The following author will discuss a simple way to clear the output from 3 perspectives

1. The output under Jupyter notebook is cleared

Mainly through IPython.display.clear_outputto empty

from IPython.display import clear_output as clear

print('before')
clear()  # 清除输出
print('after')

Specific case
Insert picture description here

2. Clear the output under Terminal/Console

Use os.system('cls')or os.system('clear')to empty

import os

print('before')
os.system('cls' if os.name == 'nt' else 'clear')
print('after')

3. Comprehensive

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')

Guess you like

Origin blog.csdn.net/SL_World/article/details/108756163