Khi chạy script Python, đôi khi cần xóa màn hình console theo chương trình (không phải phím tắt Ctrl+L).
Giải pháp cross-platform
import os
from time import sleep
def clear_screen():
"""Xóa màn hình console trên Windows, Linux, macOS"""
if os.name == 'posix': # Linux, macOS, Unix
_ = os.system('clear')
else: # Windows (nt)
_ = os.system('cls')
# Demo
print("Platform:", os.name)
print("Big output\n" * 5)
sleep(2)
clear_screen()
print("Màn hình đã được xóa!")
Kết quả
Màn hình hiển thị output 5 dòng, chờ 2 giây, sau đó xóa sạch và in "Màn hình đã được xóa!".
Giải thích
os.name: 'posix' (Linux/macOS), 'nt' (Windows)os.system(): Thực thi lệnh shell- Biến
_nhận return code (thường bỏ qua)
Cách khác: ANSI Escape Codes (chỉ terminal hỗ trợ)
def clear_screen_ansi():
print('\033[2J\033[H', end='') # Clear screen + move cursor to home
# Hoặc đơn giản hơn
print('\033c', end='') # Reset terminal
Trong Jupyter Notebook / IPython
from IPython.display import clear_output clear_output(wait=True) # Xóa output cell hiện tại
Kết luận
Dùng os.system('clear'/'cls') cho script độc lập. Dùng ANSI escape cho terminal hiện đại. Dùng IPython.display.clear_output cho notebook.