3

Tried many suggestions to clear console and variables in Spyder using code not CTRL+L but they do not work.

wondering any effective suggestion what the code can be used for clearing Spyder console and variables.

using get_ipython().magic('reset -sf') will make the variable explorer not updated.

Gamp
  • 309
  • 1
  • 5
  • 15
  • CTRL + L does clear the terminal screen but it does not clear variables--you need a kernel restart for that. What do you mean? – Rory Daulton Mar 01 '19 at 11:31

4 Answers4

13

(Spyder maintainer here) This code both clears the console and removes all variables present on the namespace at the same time:

try:
    from IPython import get_ipython
    get_ipython().magic('clear')
    get_ipython().magic('reset -f')
except:
    pass

It also has the advantage that it works inside and outside Spyder.

Note: Right now this approach generates an error in the console after it's run. We'll fix that error in the next Spyder version (3.3.4), to be released in March/2019.

Carlos Cordoba
  • 33,273
  • 10
  • 95
  • 124
  • It works. Thanks! But somewhat different with MATLAB, although variables in variable explorer are cleared, they are still shown there but not disappear. There is an option of removing all variables on the top left of the variable explorer, it can clear all variable and make them disappear. – Gamp Mar 01 '19 at 16:05
  • Ok, that's the only way I know to do what you want. If you find my answer helpful, please mark it as so by selecting the green check mark on the left. – Carlos Cordoba Mar 01 '19 at 16:14
  • Another issue caused by the code is the variable explorer is disconnected with the code, that is variables cannot be updated. Even running the code file including the code above, there is no variable shown in the variable explorer. – Gamp Mar 01 '19 at 16:45
  • @Gamp, you're totally right. I'll update my answer accordingly. – Carlos Cordoba Mar 03 '19 at 11:16
  • @CarlosCordoba Hi this one clears functions also, how can we just clears varibales in "variable explorer" – Farhang Amaji May 06 '21 at 15:20
  • Right now we don't make a difference between variables and functions, sorry. – Carlos Cordoba May 06 '21 at 15:26
  • This code now returns a warning `DeprecationWarning: magic(...) is deprecated since IPython 0.13 (warning added in 8.1), use run_line_magic(magic_name, parameter_s).`. – Austin Downey Jul 13 '22 at 14:13
  • @AustinDowney, we don't support IPython 8 yet. When we add support for it, we'll fix that warning. – Carlos Cordoba Jul 13 '22 at 22:29
5

The simplest way that I have come across to clear the Spyder console programmatically is:

print("\033[H\033[J") 

From Link and suggested by Denis Rasulev .

print("\014")

Also works.

Graham G
  • 551
  • 5
  • 14
1

cls and clear-host work in (!) the Console.

r.user.05apr
  • 5,356
  • 3
  • 22
  • 39
-2

seen it elsewhere here, not my code, but:

import os
os.system('clear')
Doj
  • 1,244
  • 6
  • 13
  • 19