[python] Clear screen in shell

Just a quick question:
How do you clear the screen in shell? I've seen ways like:

import os
os.system('cls')

This just opens the windows cmd, clears the screen and closes but I want the shell window to be cleared
(PS: I don't know this helps, but I'm using version 3.3.2 of Python)
Thank you :)

This question is related to python shell screen

The answer is


What about the shortcut CTRL+L?

It works for all shells e.g. Python, Bash, MySQL, MATLAB, etc.


I am using a class that just uses one of the above methods behind the scenes... I noticed it works on Windows and Linux... I like using it though because it's easier to type clear() instead of system('clear') or os.system('clear')

pip3 install clear-screen

from clear_screen import clear

and then when you want to clear the shell:

clear()

  1. you can Use Window Or Linux Os

    import os
    os.system('cls')
    os.system('clear')
    
  2. you can use subprocess module

    import subprocess as sp
    x=sp.call('cls',shell=True)
    

import curses
stdscr = curses.initscr()
stdscr.clear()

In addition to being an all-around great CLI library, click also provides a platform-agnostic clear() function:

import click
click.clear()

An easier way to clear a screen while in python is to use Ctrl + L though it works for the shell as well as other programs.


This function works in any OS (Unix, Linux, macOS, and Windows)
Python 2 and Python 3

import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def clear_screen():
    """
    Clears the terminal screen.
    """

    # Clear command as function of OS
    command = "cls" if platform.system().lower()=="windows" else "clear"

    # Action
    return subprocess.call(command) == 0

In windows the command is cls, in unix-like systems the command is clear.
platform.system() returns the platform name. Ex. 'Darwin' for macOS.
subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l'])


Command+K works fine in OSX to clear screen.

Shift+Command+K to clear only the scrollback buffer.


Subprocess allows you to call "cls" for Shell.

import subprocess
cls = subprocess.call('cls',shell=True)

That's as simple as I can make it. Hope it works for you!


That's the best way:

>>>import os
>>>def cls(): os.system('cls')
>>>cls()

For the Python IDLE 3.8.1 you can restart the Shell

CTRL + F6

On the menu Click on the Shell menu. Then click on the Restart Shell option.


using windows 10 and pyhton3.5 i have tested many codes and nothing helped me more than this:

First define a simple function, this funtion will print 50 newlines;(the number 50 will depend on how many lines you can see on your screen, so you can change this number)

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

then just call it as many times as you want or need

cls()

os.system('cls') works fine when I open them. It opens in cmd style.


import os

os.system('cls')  # For Windows
os.system('clear')  # For Linux/OS X

Here's how to make your very own cls or clear command that will work without explicitly calling any function!

We'll take advantage of the fact that the python console calls repr() to display objects on screen. This is especially useful if you have your own customized python shell (with the -i option for example) and you have a pre-loading script for it. This is what you need:

import os
class ScreenCleaner:
    def __repr__(self):
        os.system('cls')  # This actually clears the screen
        return ''  # Because that's what repr() likes

cls = ScreenCleaner()

Use clear instead of cls if you're on linux (in both the os command and the variable name)!

Now if you just write cls or clear in the console - it will clear it! Not even cls() or clear() - just the raw variable. This is because python will call repr(cls) to print it out, which will in turn trigger our __repr__ function.

Let's test it out:

>>> df;sag
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'df' is not defined
>>> sglknas
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sglknas' is not defined
>>> lksnldn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'lksnldn' is not defined
>>> cls

And the screen is clear!

To clarify - the code above needs to either be imported in the console like this

from somefile import cls

Or pre load directly with something like:

python -i my_pre_loaded_classes.py

If you are using linux terminal to access python, then cntrl+l is the best solution to clear screen


Here are some options that you can use on Windows

First option:

import os
cls = lambda: os.system('cls')

>>> cls()

Second option:

cls = lambda: print('\n' * 100)

>>> cls()

Third option if you are in Python REPL window:

Ctrl+L

Rather than importing all of curses or shelling out just to get one control character, you can simply use (on Linux/macOS):

print(chr(27) + "[2J")

(Source: Clear terminal in Python)


The sort of thing that you are looking for is to be found in the curses module.

i.e.

import curses  # Get the module
stdscr = curses.initscr()  # initialise it
stdscr.clear()  # Clear the screen

Important Note

The important thing to remember is before any exit, you need to reset the terminal to a normal mode, this can be done with the following lines:

curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()

If you don't you will get all sort of strange behaviour. To ensure that this is always done I would suggest using the atexit module, something like:

import atexit

@atexit.register
def goodbye():
    """ Reset terminal from curses mode on exit """
    curses.nocbreak()
    if stdscr:
        stdscr.keypad(0)
    curses.echo()
    curses.endwin()

Will probably do nicely.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to screen

How to make flutter app responsive according to different screen size? Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0 Clear screen in shell How to detect iPhone 5 (widescreen devices)? How to develop or migrate apps for iPhone 5 screen resolution? Android splash screen image sizes to fit all devices How to support different screen size in android Finish all previous activities Android screen size HDPI, LDPI, MDPI How to get the screen width and height in iOS?