How to Clear Python Shell in the Most Effective Way

We all must have experienced one common thing while working in any programming language: messy code and output. We rarely get the desired output in one go, so there are many hits and trials before that. But it is difficult to work on messy code and outputs, so we need a clear screen. If you have ever worked on C++, the function that helps us achieve this goal is clrscr().

If we are working on an interactive shell, we can quickly clear the output by simply pressing ‘Ctrl + L.’ But when we are working on IDLE, command prompt, or Linux Terminal in a running shell, we need to make our own functions to do so. So, let’s learn how to clear a Python shell.

How to Clear Python Shell?

If we are working in a REPL terminal, we can make a function using the os module to clear the output. An os module helps us to interact with our systems. A REPL terminal, also known as read–eval–print loop terminal, can be a Windows command prompt, your Linux terminal, or an Anaconda prompt. So, let us learn how to make a function to clear the Python shell.

How to Clear Python Shell in Windows Command Prompt or Anaconda Prompt?

To clear the screen in these terminals, we have first to import the os module using the code – import os.

Code-

import os

def clear_screen():
    os.system('cls')

for i in range(10):
    print(i)
clear_screen()

Output-

Here, instead of importing only the os module, we can import the system submodule with it and use the system function directly.

from os import system
system("cls")

How to Clear Python Shell in RedHat/ Ubuntu/ Centos (Linux)?

In Linux to clear the screen we cannot use the above function, so let us know how to clear the python shell.

how to clear python shell
how to clear python shell
.
import os
def clear_screen():
    os.system('clear')
for i in range(10):
    print(i)
clear_screen()
Output-

Note- I am using RedHat version-8. The procedure of starting a Python shell inside your terminal may vary from mine.

How to clear Shell in IDLE?

IDLE, or (Integrated Development and Learning Environment) is an interactive shell where we can code or write programs in Python. There is no such built-in function or way to clear the Python shell, but we have a trick by which we achieve our goal.

We cannot use the functions that we used to clear the screen in the Windows command prompt in IDLE.

Let’s see how we can do this –

def clear():
    print("\n"*47)

for i in range(20):
    print(i)
clear()
Output-

In the video above, we can clearly see that our function is just moving the prompt 47 lines down and if we scroll up, we can see the previously written code.

Must Read

Conclusion

We have learned how to clear Python Shell and most of the operating systems most effectively. We have also learned the trick to clear the screen when we do not have any built-in function for it.


Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments