如何从 Python 代码清除交互式 IPython 控制台的屏幕
How to clear the screen of Interactive IPython console from Python code
我刚刚从 Jupyter 迁移到 Spyder。在屏幕的左侧有一个显示输出的控制台。当我重新运行代码时,它会不断添加新行。我想从一个新屏幕开始。怎么样?
PS1:当我去IPyhton控制台写cls或clear时,它起作用了。但我想从 Python 代码中做到这一点。后者无法识别该命令,但 IPython 控制台可以!
PS2: 我试过了
import os
os.system('cls') # on windows
没用。它显示 CMD window 片刻然后消失。但是 Spyder 中的控制台 window 仍然显示旧错误,除了新错误。
(这里是Spyder维护者)有两种方法可以得到你想要的:
- 您可以转到菜单
Run > Configuration per file
和 select 名为 Execute in a dedicated console
的选项。该选项将在每次执行后清理您的控制台。
将以下代码添加到您的文件中:
from IPython import get_ipython
get_ipython.run_line_magic('clear', '')
Windows 蜘蛛 4,Python 3.7:
!cls
cls
cls()
Ctrl + L
clear
clear()
print(chr(27) + "[2J")
print("\x1b[2J")
clear-screen
Windows 终端,Python 3.9:
!cls
cls
Ctrl + L
cls()
print(chr(27) + "[2J")
print("\x1b[2J")
Linux 终端,Python 3.8:
Ctrl + L
clear
我刚刚从 Jupyter 迁移到 Spyder。在屏幕的左侧有一个显示输出的控制台。当我重新运行代码时,它会不断添加新行。我想从一个新屏幕开始。怎么样?
PS1:当我去IPyhton控制台写cls或clear时,它起作用了。但我想从 Python 代码中做到这一点。后者无法识别该命令,但 IPython 控制台可以!
PS2: 我试过了
import os
os.system('cls') # on windows
没用。它显示 CMD window 片刻然后消失。但是 Spyder 中的控制台 window 仍然显示旧错误,除了新错误。
(这里是Spyder维护者)有两种方法可以得到你想要的:
- 您可以转到菜单
Run > Configuration per file
和 select 名为Execute in a dedicated console
的选项。该选项将在每次执行后清理您的控制台。 将以下代码添加到您的文件中:
from IPython import get_ipython get_ipython.run_line_magic('clear', '')
Windows 蜘蛛 4,Python 3.7:
!cls
cls
cls()
Ctrl + L
clear
clear()
print(chr(27) + "[2J")
print("\x1b[2J")
clear-screen
Windows 终端,Python 3.9:
!cls
cls
Ctrl + L
cls()
print(chr(27) + "[2J")
print("\x1b[2J")
Linux 终端,Python 3.8:
Ctrl + L
clear