Python: Очистка консоли
Вы можете использовать команду os.system(‘clear’) для очистки консоли. Но этот способ работает только на операционных системах Unix-подобных, таких как Linux и macOS. На Windows эта команда не будет работать.
Способ 2: Использование команды os.system(‘cls’)
Вы можете использовать команду os.system(‘cls’) для очистки консоли на Windows. Эта команда работает только на Windows.
Способ 3: Использование модуля subprocess
Вы можете использовать модуль subprocess для выполнения команды очистки консоли, которая зависит от операционной системы. Этот способ работает как на Unix-подобных, так ии на Windows операционных системах:
Вы можете вызвать эту функцию, чтобы очистить консоль:
Этот способ позволяет вам очищать консоль независимо от операционной системы, на которой вы запускаете ваш код.
Clear Screen in Python
While working on the Python terminal (not a console)/interactive shell, some errors occur in the output. So, we have to clean the screen by pressing Control (Ctrl) and L keys simultaneously.
However, sometimes there are situations when the output has to be formatted properly to eliminate issues.
That’s why clearing the screen is based on the amount of output. In this situation, some commands need to be inserted in Python’s script to clear the screen as and when required.
So in this article, we will consider every possible way to clear the screen in Python without having any trouble or errors.
How to Clear Screen in Python Terminal
If you are working on a terminal, then use commands «cls» and «clear» to clear the terminal like this:
For Windows Users
If you are a Windows user and want to clear the screen in Python, you can easily do it using the «cls» command.
This command will instantly clear the screen, as you can see in the below image:
.jpg)
.png)
For Linux Users
Linux also has a command to clear screen in Python easily, so use the following command to do it:
.jpg)
Remember there is no specific function, built-in keywords, etc., available to clear the screen. That’s why users need to clear the screen according to them.
Clear Screen in Python Using Functions
Now let’s consider the functions we can use for clearing the screen in Python and remember that you can use these functions in both Windows and Linux.
Using click library
In this method, you can use click library to create a function, and it can work on both Windows and Linux.
Code Explanation:
In the above example, we are using click.clear() function from click library to clear screen.
This function works in Windows, Linux, and Mac operating systems.
Using \n (Newline character)
The whole way of not clearing the screen is as different as the answer is different. To remove any further error of the line, the user does not need to run the external process completely so that the screen can be cleared.
To clear the screen, you have to print new numbers which are higher than the height and can print something like this («\ n» * 10)
Code Explanation:
In the above example, we need to clear a few lined of the screen so we use “\n” with print, this will add a newline character and clear x number of lines.
Clear screen program by using os.system method
There are many OS platforms like Windows, Linux, and macOS, so we need different commands to clear the screen. So as you can see in the below syntax, we have used the ‘_’ variable for holding the value of the last expression in the interpreter.
Now we will describe the os.system method to clear the screen in Python without having any troubles. As you can see in the below syntax, we have used the os.system command because It is a string that tells which command needs to be executed.
Code Explanation:
We got «Screen Cleared» as we have printed it using the above syntax in the output.
In the above example first, we are checking if the operating system is Linux or not by checking the value of os.name method.
If the Operating system is Linux or Mac the value of os.name will be ”posix” .
And if the value of os.name is posix then we will run the function os.system(‘clear’) or else we will run function os.system(‘cls’) .
Example 2
Code Explanation:
In the above example first, we check if the platform is Windows or Linux by using platform.system() function.
If the platform is “Windows” then we store the value of a command in the variable “cmdtorun” .
And at the end of the function, we are run the function os.system(cmdtorun) with the variable “cmdtorun” .
Using Subprocess Library
In this example, we have used the subprocess() function to execute an action for clearing the screen in output.
Conclusion
So this is how you can easily clear the screen in Python using functions or commands in the Syntax. As we have mentioned earlier,
There are many methods to clear the screen in Python without getting any errors. But, in our opinion, a clear screen using a click library is the easiest because it works with both the operating systems Unix, Windows, and macOS. And it doesn’t need checking the OS.
Как очистить экран оболочки в Python
Иногда, работая с оболочкой Python, мы получали случайный вывод или писали ненужные операторы, и мы хотим очистить экран по какой-то причине.
Как очистить экран оболочки в Python? Для очистки терминала (окна терминала) используются команды «cls» и «clear». Если вы используете оболочку в IDLE, на нее такие команды не повлияют. К сожалению, в IDLE нет возможности очистить экран. Лучшее, что вы могли сделать, – это прокрутить экран вниз на множество строк.
Хотя вы можете поместить это в функцию:
А затем при необходимости вызовите его как функцию cls(). Это очистит консоль; все предыдущие команды исчезнут, и экран начнется с самого начала.
Если вы используете Linux, то –
Если вы используете Windows-
Мы также можем сделать это с помощью скрипта Python. Рассмотрим следующий пример.
Примечание. Используется переменная подчеркивания, потому что оболочка Python всегда сохраняет свой последний вывод в подчеркивании.
How to Clear Python Shell in the Most Effective Way

We all must have experienced one common thing while working in any programming language which is messy code and output. It rarely happens that we 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 to 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, 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, to clear the output, we can make a function using the os module. An os module helps us to interact with our systems. A REPL terminal also known as read–eval–print loop terminal can be windows command prompt, your Linux terminal, or 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 screen in these terminals, we have first to import the os module using the code – import os.
Code-
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 –
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 in the most effective way and most of the operating systems. We have also learned the trick to clear the screen when we do not have any built-in function for it.