Most of the time, while working with python interactive shell/terminal (not a console), we end up with a messy output and want to clear the screen for some reason.
In an interactive shell/terminal, we can simply use
But, what if we want to clear the screen while running a python script.
Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own.
We can use ANSI escape sequence but these are not portable and might not produce desired output.
So, here’s what we’re going to do in our script:
- From os import system.
- Define a function.
- Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.
- Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore).
- Call the function we defined.
NOTE: You can also only “import os” instead of “from os import system” but with that, you have to change system(‘clear’) to os.system(‘clear’).
Another way to accomplish this is using subprocess module.
- PyQt5 – How to clear the content of label | clear and setText method
- How to Get Coordinate Of Screen in Python Turtle ?
- Python Tweepy - Getting the screen name of a user
- Replace Green Screen using OpenCV- Python
- Getting screen's height and width using Tkinter | Python
- Python | How to download windows lock-screen wallpapers
- set clear() in python
- Python Dictionary clear()
- Clear LRU Cache in Python
- Python | Multiple Sliders widgets Controlling Background Screen or WindowColor in Kivy
- Different ways to clear a list in Python
- clear() element method - Selenium Python
- Python PIL | ImageChops.screen() and ImageChops.offset() method
- Matplotlib.figure.Figure.clear() in Python
- Matplotlib.axes.Axes.clear() in Python
- wxPython - Set window in center of screen
- How to Align modal content box to center of any screen?
- CSS | clear Property
- clear() method in PyQt5
- multimap clear() function in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.