203

I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.

How do I clear python's IDLE window?

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
  • 12
    it is not a duplicate, OP is asking about how to clear IDLE shell, not console – Moha the almighty camel Jan 17 '14 at 08:48
  • 2
    The reason this doesn't work is because Python starts a new shell session and runs the command `clear` in there. It also explains why `cd` doesn't work in `system.os`. – jkd Mar 22 '15 at 00:42
  • 20
    Hold down `ctrl + j` for a while and then press enter, That will be the best way – rassa45 Aug 16 '15 at 05:52
  • 1
    @ytpillai, Ah, but that gives me the prompt at the bottom. A solution, no doubt, but still causes some convenience. – John Red Feb 06 '16 at 06:28
  • Not a solution, but for anyone else that was curious, the `EditorWindow` object that the IDLEX extension uses to clear the console seems to be accessible within IDLE using (at the prompt) `inspect.currentframe().f_back.f_locals['self'].rpchandler.console`, though anything involving the `text` attribute locks up the console so it's not much help. – Christian Reall-Fluharty Dec 30 '20 at 20:30

23 Answers23

111

The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:

print ("\n" * 100)

Though you could put this in a function:

def cls(): print ("\n" * 100)

And then call it when needed as cls()

Moradnejad
  • 3,466
  • 2
  • 30
  • 52
Brian
  • 116,865
  • 28
  • 107
  • 112
108

os.system('clear') works on linux. If you are running windows try os.system('CLS') instead.

You need to import os first like this:

import os
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
  • 14
    The os.system('CLS') works in Windows. (Python 2.6). The resulting screen is cleared, only showing a "0", which I assume is the return value for CLS, at the top. The next line has the >>> prompt. – mjv Sep 16 '09 at 14:24
  • Well, it doesn't clear the python shell. But I can see the 0 print. – devoured elysium Sep 16 '09 at 15:21
  • 2
    This does not work in the Windows Idle tkinter shell, although it probably works in the command line. – Tom Feb 25 '11 at 21:43
  • 45
    this makes an os call to cls in an external command prompt and doesn't interact w/ Idle – bunglestink Dec 08 '11 at 18:29
  • In addition to Nadia's solution I suggest adding the following lines to your (PYTHONSTARTUP)[http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP] file so you can clear the screen faster: ` import os def c(): os.system('clear') ` Edit: no multiline code in comments.. but you understand my shortcut right? – Niels Bom Aug 16 '12 at 08:38
  • 15
    idle is not a console window. Both clear and cls operate on console/terminal windows. – Bryan Oakley May 19 '13 at 13:56
  • 20
    The question is 'clear screen IN IDLE' the above methods certainly do not work on my computer – Lux Nov 22 '14 at 03:16
  • 1
    @devouredelysium In a console, assign `os.system("clear")` to a variable to not see the 0. – jkd Mar 22 '15 at 00:47
  • 24
    Why is this upvoted? This will open a new command prompt, clear it, and close it – rassa45 Aug 16 '15 at 05:54
  • I'm using VS CODE on mac for teaching OOP purposes with a text-based menu system. This works on the TERMINAL WINDOW only, not the debug console. It suits my purposes for clearing before displaying a new menu. (Just clarifying why I find this answer useful) – shecodesthings Nov 08 '18 at 17:49
  • This worked for me on a windows terminal, to avoid the resulting 0 I just put it inside a funtion: ```python def cls(): os.system('cls') ``` and then just call `cls()` when I need to clear the screen – Fernando Ortega Jul 14 '21 at 23:08
  • 1
    @devouredelysium try this: _ = os.system('clear') – Teng Long Jul 19 '21 at 09:52
61

Most of the answers, here do clearing the DOS prompt screen, with clearing commands, which is not the question. Other answers here, were printing blank lines to show a clearing effect of the screen.

The simplest answer of this question is

It is not possible to clear python IDLE shell without some external module integration. If you really want to get a blank pure fresh shell just close the previous shell and run it again

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Abdul Rehman
  • 2,224
  • 25
  • 30
  • 4
    This is a good, direct, and practical answer to this question; close idle, leave the file open, run the file again and idle now has a fresh screen. – Mike_K Mar 23 '18 at 18:40
  • @Mike_K, it can be be useful, but not ever. Right now I have a splitted screen (a book <|> idle). When I reexecute the Idle, the new screen comes in the default position/dimensions. So, it will get very boring. – sdlins Mar 31 '18 at 16:34
  • 1
    So, they didn't implement the most simple thing. It didn't have to be a command, but a button in the view menu. – Moradnejad Sep 10 '20 at 17:38
52

ctrl + L clears the screen on Ubuntu Linux.

shxfee
  • 5,188
  • 6
  • 31
  • 29
26

An extension for clearing the shell can be found in Issue6143 as a "feature request". This extension is included with IdleX.

Roger
  • 951
  • 8
  • 6
20
>>> import os

>>>def cls():
...    os.system("clear")
...
>>>cls()

That does is perfectly. No '0' printed either.

David
  • 3,177
  • 1
  • 18
  • 15
Derk Smith
  • 241
  • 2
  • 2
13

There does not appear to be a way to clear the IDLE 'shell' buffer.

Mark
  • 1,639
  • 1
  • 15
  • 20
  • 1
    http://bugs.python.org/issue6143 has an extension to clear the shell, and is included with IdleX. – Roger Dec 02 '11 at 07:05
6

The way to execute commands in Python 2.4+ is to use the subprocess module. You can use it in the same way that you use os.system.

import subprocess
subprocess.call("clear") # linux/mac
subprocess.call("cls", shell=True) # windows

If you're executing this in the python console, you'll need to do something to hide the return value (for either os.system or subprocess.call), like assigning it to a variable:

cls = subprocess.call("cls", shell=True)
Rudd Zwolinski
  • 26,712
  • 17
  • 57
  • 60
  • Traceback (most recent call last): File "", line 1, in subprocess.call("cls") File "C:\Python26\lib\subprocess.py", line 444, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 2] System cannot find the specified file – devoured elysium Sep 16 '09 at 15:20
  • 1
    Hmm.. That's what I get for not using Windows and thus not being able to test it. Try subprocess.call("cls", shell=True) – Rudd Zwolinski Sep 17 '09 at 01:00
6

I like to use:

import os
clear = lambda : os.system('cls') # or clear for Linux

clear()
Luiz Domingues
  • 349
  • 7
  • 13
5

File -> New Window

In the new window**

Run -> Python Shell

The problem with this method is that it will clear all the things you defined, such as variables.

Alternatively, you should just use command prompt.

open up command prompt

type "cd c:\python27"

type "python example.py" , you have to edit this using IDLE when it's not in interactive mode. If you're in python shell, file -> new window.

Note that the example.py needs to be in the same directory as C:\python27, or whatever directory you have python installed.

Then from here, you just press the UP arrow key on your keyboard. You just edit example.py, use CTRL + S, then go back to command prompt, press the UP arrow key, hit enter.

If the command prompt gets too crowded, just type "clr"

The "clr" command only works with command prompt, it will not work with IDLE.

  • 3
    Just Saying, but I believe that the question is asking 'How do you clear the screen IN IDLE FROM INSIDE THE PYTHON SCRIPT. – Lux Nov 22 '14 at 03:18
  • Starting new file and running Python shell in it appeared to be the only option available to me, nothing else worked. Thanks! – Sergey Zakharov Jul 22 '19 at 21:11
5

"command + L" for MAC OS X.

"control + L" for Ubuntu

Clears the last line on the interactive session

JamCon
  • 2,313
  • 2
  • 25
  • 34
Darshan N S
  • 97
  • 1
  • 4
5

It seems like there is no direct way for clearing the IDLE console.

One way I do it is use of exit() as the last command in my python script (.py). When I run the script, it always opens up a new console and prompt before exiting.

Upside : Console is launched fresh each time the script is executed. Downside : Console is launched fresh each time the script is executed.

Sandeep Gaadhe
  • 367
  • 4
  • 4
3

As mark.ribau said, it seems that there is no way to clear the Text widget in idle. One should edit the EditorWindow.py module and add a method and a menu item in the EditorWindow class that does something like:

self.text.tag_remove("sel", "1.0", "end")
self.text.delete("1.0", "end")

and perhaps some more tag management of which I'm unaware of.

tzot
  • 92,761
  • 29
  • 141
  • 204
3

None of these solutions worked for me on Windows 7 and within IDLE. Wound up using PowerShell, running Python within it and exiting to call "cls" in PowerShell to clear the window.

CONS: Assumes Python is already in the PATH variable. Also, this does clear your Python variables (though so does restarting the shell).

PROS: Retains any window customization you've made (color, font-size).

Draghon
  • 347
  • 3
  • 9
  • How did you do this: "Wound up using PowerShell, running Python within it and exiting to call "cls" in PowerShell to clear the window" ? – Just Me Sep 14 '22 at 09:27
3

It seems it is impossible to do it without any external library.

An alternative way if you are using windows and don't want to open and close the shell everytime you want to clear it is by using windows command prompt.

  • Type python and hit enter to turn windows command prompt to python idle (make sure python is installed).

  • Type quit() and hit enter to turn it back to windows command prompt.

  • Type cls and hit enter to clear the command prompt/ windows shell.

Ari
  • 4,643
  • 5
  • 36
  • 52
2

The best way to do it on windows is using the command prompt 'cmd' and access python directory the command prompt could be found on the start menu >run>cmd

C:\>cd Python27
C:\Python27>python.exe
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>import os
>>>os.system('cls')  #This will clear the screen and return the value 0
Al-Ani
  • 57
  • 4
  • 2
    Just Saying, but I believe that the question is asking 'How do you clear the screen IN IDLE'. (Emphasis on `IN IDLE`) – Lux Nov 22 '14 at 03:22
2

You can make an AutoHotKey script.

To set ctrl-r to a hotkey to clear the shell:

^r::SendInput print '\n' * 50 {Enter}

Just install AutoHotKey, put the above in a file called idle_clear.ahk, run the file, and your hotkey is active.

Scruffy
  • 908
  • 1
  • 8
  • 21
1

I would recommend you to use Thonny IDE for Python. It's shell has "Clear Shell" option and you can also track variables created in a separate list. It's debugging is very good even comparing with modern IDEs. You can also write code in python file along with access to shell at the same place.

And its lightweight!

Zaheer
  • 374
  • 4
  • 20
0

use this

for num in range(1,100):
    print("\n")
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Tauseef
  • 369
  • 3
  • 15
0

Turtle can clear the screen.

#=====================================
import turtle

wn = turtle.Screen()
wn.title("Clear the Screen")

t = turtle.Turtle()
t.color('red', 'yellow')
t.speed(0)

#=====================================

def star(x, y, length, angle):
    t.penup()
    t.goto(x, y)
    t.pendown()
    t.begin_fill()
    while True:
        t.forward(length)
        t.left(angle)
        if t.heading() == 0: #===============
            break
    t.end_fill()
#=====================================
#   (  x,    y,  length, angle)
star(-360,  0,    150,    45)
t.clear()
#=====================================
user1839239
  • 71
  • 1
  • 1
  • 5
0

This answer is for IDLE, not for the command prompt and was tested with Python 3.10.6.

If you press Ctrl+Z while the code is running (before it finishes), the previous output will be erased. If you wish to automate this, there's the pynput package.

pip install pynput

Here's a sample code (macros are unsafe, use it at your own risk):

# License: MIT-0
import time
import pynput

class _Eraser:
    keyboard = pynput.keyboard.Controller()
    ctrl = pynput.keyboard.Key.ctrl
    is_initialized = False

    @classmethod
    def erase(cls, n):
        if not cls.is_initialized:
            cls.is_initialized = True
            n += 1
        for _ in range(n):
            with cls.keyboard.pressed(cls.ctrl):
                cls.keyboard.press('z')
                cls.keyboard.release('z')
        time.sleep(0.1)

def erase(n=1):
    _Eraser.erase(n)

print('test1\n', end='')
print('test2\n', end='')
erase()  # Erase 'test2\n'
print('test3')
print('test4')
erase()  # Erase '\n'
print('test5')
print('test6')
erase(2)  # Erase '\n' and then 'test6'
print('test7')

The output is:

test1
test3
test4test5
test7
Wood
  • 271
  • 1
  • 8
-3

This works for me in Windows:

print chr(12)

Joel Vroom
  • 1,611
  • 1
  • 16
  • 30
-8

There is no need to write your own function to do this! Python has a built in clear function.

Type the following in the command prompt:

shell.clear()

If using IPython for Windows, it's

cls()
jeremysprofile
  • 10,028
  • 4
  • 33
  • 53
  • 5
    Is there some kind of import required for doing this, because it didn't work for me. If there is an import involved, you should put it into your response. Also, the question is about clearing the prompt _IN IDLE_. – Lux Dec 13 '14 at 03:05