Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xóa màn hình terminal khi chạy script Python

Không có hàm built-in để xóa màn hình trong script Python, nhưng có thể thực hiện qua module os hoặc subprocess.

Cách 1: Sử dụng os.system()

from os import system, name
from time import sleep

def screen_clear():
    if name == 'nt':          # Windows
        _ = system('cls')
    else:                     # Linux/macOS (posix)
        _ = system('clear')

# Demo
print('Hi !! I am Python\n' * 10)
sleep(2)
screen_clear()

Cách 2: Sử dụng subprocess.call()

import os
from subprocess import call
from time import sleep

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

print('Hi !! I am Python\n' * 10)
sleep(2)
screen_clear()

Kết quả

Màn hình in 10 dòng "Hi !! I am Python", chờ 2 giây, sau đó xóa sạch.

Lưu ý

  • Trong IDE (PyCharm, VS Code terminal) có thể không hoạt động như terminal thật.
  • Biến _ dùng để lưu giá trị trả về (thông lệ bỏ qua).
  • Trên Windows dùng cls, Linux/macOS dùng clear.