Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the screen of Interactive IPython console from Python code

I have just migrated from Jupyter to Spyder. On the left of the screen there is a console that shows the output. When I rerun the code it keeps adding new lines. I want to start with a new screen. How?

PS1: When I go to the IPyhton console and write cls or clear, it works. But I want to do that from Python code. The latter doesn't recognize that command, but IPython console does!

PS2: I've tried

import os 
os.system('cls')  # on windows

It didn't work. It shows a CMD window for a moment and vanishes. But the console window in Spyder still shows the old errors, besides the new ones.

like image 855
Alex Deft Avatar asked Aug 07 '26 08:08

Alex Deft


2 Answers

Windows Spyder 4, Python 3.7:

  • !cls
  • cls
  • cls()
  • Ctrl + L
  • clear
  • clear()
  • print(chr(27) + "[2J")
  • print("\x1b[2J")
  • clear-screen

Windows Terminal, Python 3.9:

  • !cls
  • cls
  • Ctrl + L
  • cls()
  • print(chr(27) + "[2J")
  • print("\x1b[2J")

Linux Terminal, Python 3.8:

  • Ctrl + L
  • clear
like image 128
Szczerski Avatar answered Aug 09 '26 04:08

Szczerski


(Spyder maintainer here) There are two ways to get what you want:

  1. You can go to the menu Run > Configuration per file and select the option called Execute in a dedicated console. That option will clean your console after every execution.
  2. Add the following code to your file:

    from IPython import get_ipython
    get_ipython.run_line_magic('clear', '')
    
like image 38
Carlos Cordoba Avatar answered Aug 09 '26 02:08

Carlos Cordoba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!