jupyterbook 清空控制台输出

我们在 jupyter notebook参数化运行python 时,怕输出太多文件太大,想及时清除 notebook 的输出。可以使用如下方式来解决。

1. 安装包

pip install easydl

2. 在程序中调用即可

# 1.导包
from easydl import clear_output

print('before')
# 在合适的地方插入此代码,一般是循环等处
clear_output() # 清除输出
print('after')

3. 具体实例演示

jupyterbook 清空控制台输出_第1张图片

4. 问题排错

但是,引用clear_output后,在程序运行时,有时候会报乱七八糟的错误,比如笔者下面的报错。

在这里插入图片描述

其实类似的报错也有很多,我们去看它的源码,发现clear_output方法非常简单。如下所示:

def clear_output():
    """
    clear output for both jupyter notebook and the console
    """
    import os
    os.system('cls' if os.name == 'nt' else 'clear')
    if is_in_notebook():
        from IPython.display import clear_output as clear
        clear()

既然它源码这样写,我们可以直接使用它源码中的方法,即可轻松解决遇到的问题。

from IPython.display import clear_output as clear

print('before')
# 在合适的地方插入此代码,一般是循环等处
clear() # 清除输出
print('after')

或者也可以改为如下:

from IPython.display import clear_output

print('before')
# 在合适的地方插入此代码,一般是循环等处
clear_output() # 清除输出
print('after')

你可能感兴趣的:(科研,Python,python,开发语言)