Очистить командную строку windows python

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Быстрый ответ

Чтобы очистить консоль в Python, примените следующий код:

Данная команда определяет операционную систему и исполняет соответствующую ей команду: "cls" для Windows и "clear" для Unix/Linux. После её запуска, терминал будет очищен.

Кинга Идем в IT: пошаговый план для смены профессии

Расширяем набор инструментов

Рассмотрим несколько других методов для очистки терминала при помощи стандартной библиотеки Python:

Управление терминалом с использованием escape-последовательностей

Экран можно очистить при помощи escape-последовательностей:

Если \033[H перемещает курсор в верхний левый угол экрана, то уже после этого \033[J очищает экран.

Subprocess: мощный инструмент

При помощи модуля subprocess можно получить больший контроль:

Модуль subprocess позволяет управлять выполнением команд с большей точностью.

Поддержка очистки буфера прокрутки

В Linux и macOS не только нужно очищать видимую часть консоли, но и буфер прокрутки:

В данном случае, \033c сбрасывает состояние терминала, а \033[3J очищает буфер прокрутки.

Управление терминалом и работа с курсором

Способность правильно управлять курсором и буфером увеличивает продуктивность работы:

Очистка без добавления новой строки

Вы можете очистить экран, сохранив текущее положение курсора:

Почистить экран с помощью subprocess

Для очистки экрана вы можете использовать команду printf через модуль subprocess:

Стилизация курсора

Можно изменить вид курсора при помощи escape-кодов:

Визуализация

Пример демонстрации работы команды очистки:

Кроссплатформенные решения

Для универсальной очистки терминала и работы с файлами можно использовать модуль shutil.

Очистка терминала с помощью модуля shutil

Модуль shutil позволяет совместно управлять терминалом и производить файловые операции.

За рамками традиционных команд терминала

Python обладает возможностями, выходящими за рамки стандартной работы с терминалом:

Использование библиотек GUI

Рассмотрите использование графических библиотек, таких как Tkinter или PyQt, для создания интерфейсов с функциями очистки экрана.

Интеграция с IDE

В интегрированных средах разработки и редакторах кода используйте специализированные команды для очистки терминала.

Полезные материалы

  1. Документация Python по модулю os.
  2. Обсуждение очистки терминала в Python на Stack Overflow.
  3. Как очистить консоль интерпретатора Python на Stack Overflow.
  4. Руководство по использованию модуля subprocess.
  5. Обзор shell-команд в Python от Real Python.
  6. Руководство по очистке экрана в Python от GeeksforGeeks.
  7. Введение в использование модуля shutil.

This tutorial helps How to Clear the Console in Python. There is a number of ways to clear the console based on the operating system. You can also clear the interpreter programmatically.

There are several methods for clearing the console in Python, depending on the operating system you are using.

Here, we’ll go over the most popular Python techniques for clearing the console in this article. We’ll use os the library, which is a built-in library that comes with Python3 installations.

You can also checkout other python tutorials:

  • Encode and Decode String in Python
  • What is numpy.ones() and uses
  • Python do while with Example
  • How To Compare Two Numpy Arrays
  • How to Use Logging in Python

Method 1: Using the os module

Import the os module and use its os.system() function to wipe the console in Python.

Let’s import os module:

import os

Clear Console in Linux system

We’ll use the os.system('clear') command to clear the console.

The Sample code:

import os

def clear_console():
    os.system('clear')

clear_console()

The screen will be cleared if the above command is entered into your console.

Clear Console in Windows system

For the Windows system, We’ll use the os.system('cls') command to clear the console.

The Sample code:

import os

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

clear_console()

Run the above command in your terminal to clear the screen.

Method 2: Using the subprocess module

The subprocess module provides a way to run shell commands from within your Python code. To clear the console in Python.

import subprocess

# For Windows
subprocess.call('cls', shell=True)

# For Linux/Unix
subprocess.call('clear', shell=True)

Method 3: Using ANSI escape codes

You can also clear the console using the ANSI escape codes, The ANSI escape codes are sequences of characters that control formatting, color, and other visual effects in the console.

The majority of terminals, including the Windows Command Prompt, Git Bash, and terminal emulators for Linux and macOS, are compatible with this method.

Lambda Function To Clear Console in Python

You can also use the lambda function to clear the python console.

import os
def clear_console(): return os.system('clear')

clear_console()

The screen will be cleared if the above code will run.

Conclusion

We have learned different ways to clear the console in python. Clearing the console in Python is a simple task that can be done using the os module, the subprocess module, or ANSI escape codes.

  1. Method 1: Using os.system for Windows

  2. Method 2: Using os.system for Unix/Linux

  3. Method 3: Using ANSI Escape Sequences

  4. Method 4: Using a Custom Function

  5. Conclusion

  6. FAQ

How to Clear Console in Python

When working with Python, especially during development and debugging, you might find yourself needing to clear the console for better readability. A cluttered console can be distracting and hinder your workflow. Whether you’re running scripts in an IDE, terminal, or command prompt, knowing how to clear the console can enhance your coding experience.

In this article, we will explore various methods to clear the console in Python, providing clear examples and explanations. By the end, you’ll be equipped with the knowledge to keep your console clean and your focus sharp.

Method 1: Using os.system for Windows

One of the easiest ways to clear the console in Python on Windows is by using the os module. The os.system() function allows you to execute shell commands directly from your Python script. To clear the console, you can use the cls command, which is specific to Windows.

Here’s how you can do it:

import os

os.system('cls')

Output:

This code snippet imports the os module, which provides a way of using operating system-dependent functionality. The os.system('cls') command then executes the cls command in the command prompt, effectively clearing the console. This method is straightforward and works seamlessly in a Windows environment.

However, it’s essential to remember that this method is specific to Windows. If you try to use it in a Unix-like environment, you will not see the desired effect. Therefore, it’s crucial to choose the right command based on your operating system.

Method 2: Using os.system for Unix/Linux

If you are working in a Unix-like environment, such as Linux or macOS, clearing the console is just as easy, but the command differs. Instead of cls, you will use the clear command. Here’s how you can implement this in Python:

import os

os.system('clear')

Output:

Similar to the previous method, this code snippet uses the os module to execute the clear command. When you run this code, it will clear all previous output in the terminal, giving you a fresh slate to work with. This method is efficient and widely used among developers who prefer working in Unix-like environments.

Again, it’s crucial to note that this command is specific to Unix-based systems. Attempting to use it on Windows will not yield the desired results. Always ensure you are using the appropriate command for your operating system to avoid confusion.

Method 3: Using ANSI Escape Sequences

Another method to clear the console in Python is by using ANSI escape sequences. This approach can be particularly useful if you want a solution that works across different operating systems, including Windows, Linux, and macOS. Here’s how to do it:

import sys

def clear_console():
    sys.stdout.write("\033[2J\033[H")
    sys.stdout.flush()

clear_console()

Output:

In this code, we define a function called clear_console(). The sys.stdout.write() method sends the ANSI escape sequences to the console. The sequence \033[2J clears the screen, and \033[H moves the cursor back to the top-left corner of the console. The sys.stdout.flush() method ensures that the output is immediately visible in the console.

This method is advantageous because it does not rely on the operating system’s specific commands, making it more versatile. It’s a great option if you are developing cross-platform applications and want to maintain consistency in your console output.

Method 4: Using a Custom Function

If you prefer a more customizable approach, you can create a function that checks the operating system and clears the console accordingly. This method combines the previous approaches and provides a unified solution for all environments. Here’s an example:

import os
import platform

def clear_console():
    if platform.system() == "Windows":
        os.system('cls')
    else:
        os.system('clear')

clear_console()

Output:

In this code, we import the platform module to determine the operating system. The clear_console() function checks if the system is Windows and executes the appropriate command (cls for Windows and clear for Unix-like systems). This method is efficient and ensures that your code remains clean and adaptable to different environments.

By using this custom function, you can easily integrate console-clearing functionality into your larger Python applications without worrying about compatibility issues.

Conclusion

Clearing the console in Python is a simple yet effective way to enhance your coding experience. Whether you’re using the os module, ANSI escape sequences, or creating a custom function, there are various methods to achieve a clean console. By incorporating these techniques into your workflow, you can maintain focus and clarity while developing your Python applications. Remember to choose the method that best fits your operating system and coding style, and enjoy a more organized coding environment.

FAQ

  1. How do I clear the console in Python on Windows?
    You can use the os.system('cls') command to clear the console in Python on Windows.

  2. What command should I use to clear the console in Unix/Linux?
    Use the os.system('clear') command to clear the console in Unix/Linux environments.

  3. Can I use ANSI escape sequences to clear the console?
    Yes, you can use ANSI escape sequences like \033[2J\033[H to clear the console across different operating systems.

  4. Is there a universal method to clear the console in Python?
    Yes, you can create a custom function that checks the operating system and uses the appropriate command to clear the console.

  5. Why is it important to clear the console while coding?
    Clearing the console helps improve readability and focus, making it easier to debug and develop your Python applications.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Last Updated :
21 Apr, 2025

When working in the Python interactive shell or terminal (not a console), the screen can quickly become cluttered with output. To keep things organized, you might want to clear the screen. In an interactive shell/terminal, we can simply use

ctrl+l

But, if we want to clear the screen while running a python script, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own as shown below:

Clearing Screen in Windows

1. Using cls

You can use the cls command to clear the screen in Windows. This can be done by running the following command via os.system() or subprocess.

Python

import os

# Clearing the Screen
os.system('cls')

Output

Initially:

clearScreen1

Before cls

After clearing screen:

clearScreen2

After cls

2. Using os.system(‘clear’)

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’). 

Python

from os import system, name
from time import sleep

if name == 'nt':
    _ = system('cls')
else:
    _ = system('clear')

print('hello geeks\n'*10)

sleep(2)

Explanation:

  • if name == ‘nt’ checks if the operating system is Windows (‘nt’ stands for Windows).
  • system(‘cls’) is used to clear the screen in Windows.
  • else: If the system is macOS or Linux (where os.name is ‘posix’), it uses system(‘clear’) to clear the screen.

3. Using subprocess.call()

Another way to clear the screen is by using the subprocess module, which allows you to execute system commands. This method can be used to invoke either cls or clear based on the operating system.

Python

from subprocess import call
from time import sleep
import os

print('hello geeks\n'*10)

sleep(2)

_ = call('clear' if os.name == 'posix' else 'cls')

Explanation:

  • call(): This function from the subprocess module runs the specified command in the terminal.
  • os.name == ‘posix’: Checks if the operating system is macOS or Linux. If it is, it runs clear to clear the terminal screen.
  • ‘cls’: If the system is Windows, it runs cls to clear the screen.

Clearing Screen in Linux

In this example, we used the time module and os module to clear the screen in Linux os.

Python

import os
from time import sleep

# some text
print("a")
print("b")
print("c")
print("d")
print("e")
print("Screen will now be cleared in 5 Seconds")

# Waiting for 5 seconds to clear the screen
sleep(5)

# Clearing the Screen
os.system('clear')

Overview

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.

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.

Introduction to Python Clear Screen

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:

Clearing Screen in Windows Operating System

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:

Clearing the screen then printing

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:

 check the os name and then accordingly apply the function

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.

  • Clearing Screen can be done programmatically, and also it helps us to format the output the way we want.
  • For clearing the console in the windows operating system, we will use the system() method from the os module with the ‘cls’ parameter.
  • For clearing the console in Linux operating system, we will use the system() method from the os module with the ‘clear’ parameter.
  • For windows, the os name is nt, and for Linux, it is posix, so we can also first determine the os and then clear the screen.

Read More

1- What is clear() in Python?

2 — How to install python in linux?

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows privacy dashboard github
  • Windows 10 by eagle 123
  • Hp scanjet pro 3000 s3 драйвер для windows 10
  • Удаление предустановленных uwp appx приложений в windows 10
  • Как убрать пароль при входе в windows 7 профессиональная