How to Clear Screen in Python?
Python os module is imported to clear the console screen in any operating system. The system() method of the os module with the string cls or clear as a parameter is used to clear the screen in windows and macOS/Linux, respectively.
Scope
- This article will teach us how to clear the console screen in different operating systems.
- We will use the os module and its system() method.
- We will learn about clear and cls commands and how to use them as a string parameter to the system() method.
Introduction to Python Clear Screen
Suppose there is a case where you have given the information of 3 students, and you have to print their details in a way like first there will be information of student 1 , then after some time information of student 2 will be displayed and then finally the information of student 3 will be displayed. So, in that case, we will have to clear the python console each time after displaying information about each student.
Image Explanation of the above Example
In an interactive shell/terminal , to clear the python console, we can use the ctrl+l command, but in most cases, we have to clear the screen while running the python script, so we have to do it programmatically.
We can clear screen programmatically, and it helps us to format the output in the way we want. We can also clear the output whenever we want many numbers of times.
How to clear the python console screen?
Clearing the console in python has different methods for different Operating Systems. These are stated below:
- In Windows: For clearing the console in the windows operating system, we will use the system() function from the os module with the 'cls' parameter.
Syntax of the system() function: system() function is in the os module, so the os module needs to be imported before using the system() function in Windows. After importing the os module, the string parameter 'cls' is passed inside the system function to clear the screen.
- In Linux and MacOS: For clearing the console in Linux and Mac operating systems, we will use the system() function from the os module with the 'clear' parameter.
Syntax: os module needs to be imported before using the system() function in Linux. After importing the os module string value parameter 'clear' is passed inside the system function to clear the screen.
- Ctrl+l: This method only works for Linux operating system. In an interactive shell/terminal, we can simply use ctrl+l to clear the screen.
Example of Python Clear Screen
Example 1: Clearing Screen in Windows Operating System
Let's look at an example of the clear screen in python to clarify our understanding.
We will use the above-stated system() function for clearing the python console.
First, we will print some Output; then we will wait for 4 seconds using the sleep() function to halt the program for 4 seconds, and after that, we will apply os.system('cls') to clear the screen.
Code:
Output:
The output window will print the given text first, then the program will sleep for 4 seconds, then the screen will be cleared, and program execution will be stopped.
Example 2: Clearing the screen, then printing some more information in Windows Operating System.
First we will print some Output, then we will wait for 1 second using the sleep() function, and after that, we will apply os.system('cls') to clear the screen.
After that, we will print some more information.
Code:
Output:
The output window will print the first information, then the program will sleep for 1 second, and the screen will be cleared, and then it will print the second information. Again the program will sleep for 1 second, and at last, the program will be stopped after printing the final batch of information.
Example 3: Clearing Screen in Linux Operating System
We will use the above-stated system() method for clearing the python console.
First, we will print some Output; then we will wait for 5 seconds using the sleep() function, and after that, we will apply os.system('clear') to clear the screen.
Code:
Output:
- After 5 seconds, the screen is cleared.
The output window will print the given text first, then the program will sleep for 5 seconds, then the screen will be cleared, and program execution will be stopped.
Example 4: What if we don't know what OS we are working on?
There can be a case where we must first determine what OS we are working on. So, we will first determine whether the os is Windows, Linux, or Mac.
For Windows, the os name is "nt" and for Linux or mac, the OS name is "posix".
So we will check the os name and then accordingly apply the function.
Code:
Output:
For this case, the os name is nt , so windows console will be cleared after 2 seconds of program sleep, and then it will be terminated.
Conclusion
Now that we have seen various examples of how to clear the screen in python let us note down a few points.
Использование интерактивной консоли Python
Интерактивная консоль Python (также интерпретатор или оболочка Python) предоставляет программистам быстрый способ выполнить команды и протестировать код, не создавая файл.
Интерактивная консоль предоставляет доступ к истории команд, всем встроенным функциям и установленным модулям Python. Она позволяет использовать автозаполнение, исследовать возможности Python и вставлять код в файлы программирования после проверки.
Этот мануал научит вас работать с интерактивной консолью Python.
Доступ к интерактивной консоли
Доступ к интерактивной консоли Python можно получить с любого локального компьютера или сервера, на котором установлен Python.
Для входа в интерактивную консоль Python используйте команду:
Если вы настроили среду разработки, вы можете получить доступ к консоли внутри этой среды. Сначала запустите среду:
cd environments
my_env/bin/activate
Затем откройте консоль:
Читайте также:
В этом случае по умолчанию используется версия Python 3.5.2, которая отображается на выходе вместе с уведомлением об авторских правах и командами для дополнительной информации:
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type «help», «copyright», «credits» or «license» for more information.
>>>
Поле для ввода следующей команды – три знака больше:
Вы можете указать определенную версию Python, добавив номер версии в команду без пробелов:
$ python2.7
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type «help», «copyright», «credits» or «license» for more information.
>>>
Вывод сообщает, что теперь будет использоваться версия Python 2.7.12. Если бы она была версией Python по умолчанию, открыть её интерактивную консоль можно было бы с помощью команды python2.
Чтобы вызвать интерактивную консоль версии Python 3 по умолчанию, нужно ввести:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type «help», «copyright», «credits» or «license» for more information.
>>>
Также консоль этой версии можно вызвать с помощью команды:
Работа с интерактивной консолью Python
Интерактивный интерпретатор Python принимает синтаксис Python, который находится после префикса >>>.
Например, он позволяет присваивать значения переменным:
Вы можете присвоить значения нескольким переменным, чтобы обрабатывать математические операции.
>>> birth_year = 1868
>>> death_year = 1921
>>> age_at_death = death_year — birth_year
>>> print(age_at_death)
53
>>>
Как и в файле, в консоли можно задать значения переменных, выполнить математическую операцию и запросить результат.
Интерактивную консоль можно использовать как калькулятор.
Многострочный код Python в консоли
При создании многострочного кода в консоли интерпретатор Python использует троеточие (…) в качестве вспомогательной строки.
Чтобы выйти из вспомогательной строки, нужно дважды нажать Enter.
Чтобы понять, как это работает, рассмотрите этот код, который задает значения двум переменным и использует условное выражение, чтобы определить вывод.
>>> 8host = ‘8host’
>>> blog = ‘blog’
>>> if len(8host) > len(blog):
. print(‘8host codes in Java.’)
. else:
. print(‘8host codes in Python.’)
.
8host codes in Java.
>>>
В данном случае первая строка длиннее, чем вторая, потому срабатывает первое условие и программа выводит соответствующую строку.
Обратите внимание, при этом нужно соблюдать соглашение об отступах Python (четыре пробела), иначе вы получите сообщение об ошибке:
>>> if len(8host) > len(blog):
. print(‘8host codes in Java.’)
File «<stdin>», line 2
print(‘8host codes in Java.’)
^
IndentationError: expected an indented block
>>>
Импорт модулей
Интерпретатор Python позволяет быстро проверить, доступны ли те или иные модули в определенной среде программирования. Для этого существует оператор import:
>>> import matplotlib
Traceback (most recent call last):
File «<stdin>», line 1, in <module>
ImportError: No module named ‘matplotlib’
В данном случае библиотека matplotlib недоступна в текущей среде.
Чтобы установить эту библиотеку, используйте pip.
pip install matplotlib
Collecting matplotlib
Downloading matplotlib-2.0.2-cp35-cp35m-manylinux1_x86_64.whl (14.6MB)
.
Installing collected packages: pyparsing, cycler, python-dateutil, numpy, pytz, matplotlib
Successfully installed cycler-0.10.0 matplotlib-2.0.2 numpy-1.13.0 pyparsing-2.2.0 python-dateutil-2.6.0 pytz-2017.2
Установив модуль matplotlib и его зависимости, вы можете вернуться в интерактивный интерпретатор.
Теперь вы можете использовать импортированный модуль в этой среде.
Выход из интерактивной консоли Python
Закрыть консоль Python можно двумя способами: с помощью клавиатуры или с помощью функции Python.
Чтобы закрыть консоль, можно нажать на клавиатуре Ctrl + D в *nix-подобных системах или Ctrl + Z + Ctrl в Windows.
>>> age_at_death = death_year — birth_year
gt;>> print(age_at_death)
53
>>>
8host@ubuntu:
Также в Python есть функция quit(), которая закрывает консоль и возвращает вас в стандартный терминал.
Функция quit() записывается в историю, а комбинации клавиш – нет. Это следует учитывать при выходе из консоли. Откройте файл истории /home/8host /.python_history
.
age_at_death = death_year — birth_year
print(age_at_death)
octopus = ‘Ollie’
quit()
История консоли Python
Еще одним преимуществом интерактивной консоли Python является история. Все команды регистрируются в файле .python_history (в *nix-подобных системах).
На данный момент файл истории Python выглядит так:
import pygame
quit()
if 10 > 5:
print(«hello, world»)
else:
print(«nope»)
8host = ‘8host’
blog = ‘blog’
.
Чтобы закрыть файл, нажмите Ctrl + X.
Отслеживая историю, вы можете вернуться к предыдущим командам, скопировать, вставить или изменить этот код, а затем использовать его в файлах программы или Jupyter Notebook.
Заключение
Интерактивная консоль Python предоставляет пространство для экспериментов с кодом Python. Вы можете использовать ее как инструмент для тестирования, разработки логики программы и многого другого.
Для отладки файлов программы Python вы можете использовать модуль code и открыть интерактивный интерпретатор внутри файла.
How to hide console window in python?
I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.
What can I do for that?
10 Answers 10
Simply save it with a .pyw extension. This will prevent the console window from opening.
On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.
In linux, just run it, no problem. In Windows, you want to use the pythonw executable.
Update
Okay, if I understand the question in the comments, you’re asking how to make the command window in which you’ve started the bot from the command line go away afterwards?
- UNIX (Linux)
- Windows
I think that’s right. In any case, now you can close the terminal.
On Unix Systems (including GNU/Linux, macOS, and BSD)
Use nohup mypythonprog & , and you can close the terminal window without disrupting the process. You can also run exit if you are running in the cloud and don’t want to leave a hanging shell process.
On Windows Systems
Save the program with a .pyw extension and now it will open with pythonw.exe . No shell window.
For example, if you have foo.py , you need to rename it to foo.pyw .
![]()
This will hide your console. Implement these lines in your code first to start hiding your console at first.
Update May 2020 :
If you’ve got trouble on pip install win32con on Command Prompt, you can simply pip install pywin32 .Then on your python script, execute import win32.lib.win32con as win32con instead of import win32con .
To show back your program again win32con.SW_SHOW works fine:
![]()
If all you want to do is run your Python Script on a windows computer that has the Python Interpreter installed, converting the extension of your saved script from ‘.py’ to ‘.pyw’ should do the trick.
Python exit command (quit(), exit(), sys.exit())
Let us check out the exit commands in python like quit(), exit(), sys.exit() commands.
Python quit() function
In python, we have an in-built quit() function which is used to exit a python program. When it encounters the quit() function in the system, it terminates the execution of the program completely.
It should not be used in production code and this function should only be used in the interpreter.
Example:
After writing the above code (python quit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to quit, and it will print the quit message.
You can refer to the below screenshot python quit() function.

Python exit() function
We can also use the in-built exit() function in python to exit and come out of the program in python. It should be used in the interpreter only, it is like a synonym of quit() to make python more user-friendly
Example:
After writing the above code (python exit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to exit, and it will print the exit message too.
You can refer to the below screenshot python exit() function.

Python sys.exit() function
In python, sys.exit() is considered good to be used in production code unlike quit() and exit() as sys module is always available. It also contains the in-built function to exit the program and come out of the execution process. The sys.exit() also raises the SystemExit exception.
Example:
After writing the above code (python sys.exit() function), the output will appear as a “ Marks is less than 20 “. Here, if the marks are less than 20 then it will exit the program as an exception occurred and it will print SystemExit with the argument.
You can refer to the below screenshot python sys.exit() function.

Python os.exit() function
So first, we will import os module. Then, the os.exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers.
Example:
After writing the above code (python os.exit() function), the output will appear as a “ 0 1 2 “. Here, it will exit the program, if the value of ‘i’ equal to 3 then it will print the exit message.
You can refer to the below screenshot python os.exit() function.

Python raise SystemExit
The SystemExit is an exception which is raised, when the program is running needs to be stop.
Example:
After writing the above code (python raise SystemExit), the output will appear as “ 0 1 2 3 4 “. Here, we will use this exception to raise an error. If the value of ‘i’ equal to 5 then, it will exit the program and print the exit message.
You can refer to the below screenshot python raise SystemExit.

Program to stop code execution in python
To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.
Example:
After writing the above code (program to stop code execution in python), the output will appear as a “ list length is less than 5 “. If you want to prevent it from running, if a certain condition is not met then you can stop the execution. Here, the length of “my_list” is less than 5 so it stops the execution.
You can refer to the below screenshot program to stop code execution in python.

Difference between exit() and sys.exit() in python
- exit() – If we use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. The exit() is considered bad to use in production code because it relies on site module.
- sys.exit() – But sys.exit() is better in this case because it closes the program and doesn’t ask. It is considered good to use in production code because the sys module will always be there.
In this Python tutorial, we learned about the python exit command with example and also we have seen how to use it like:
- Python quit() function
- Python exit() function
- Python sys.exit() function
- Python os.exit() function
- Python raise SystemExit
- Program to stop code execution in python
- Difference between exit() and sys.exit() in python

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.