Python 콘솔 화면 지우기
Python 콘솔 화면 지우기입니다. os.system, Windows cls, Linux/macOS clear, subprocess, ANSI escape와 메뉴 프로그램 예제를 정리했습니다.
Python 콘솔 화면 지우기
Python 콘솔 프로그램을 만들다 보면 메뉴를 다시 그리거나 이전 출력 내용을 정리하고 싶을 때가 있다. 화면 지우기는 운영체제별 명령이 다르므로 Windows는 cls, Linux/macOS는 clear를 사용한다.
가장 단순한 방법
import os
os.system("cls") # Windows
os.system("clear") # Linux, macOS운영체제 자동 판별
import os
def clear_console() -> None:
command = "cls" if os.name == "nt" else "clear"
os.system(command)
if __name__ == "__main__":
input("Enter를 누르면 화면을 지웁니다.")
clear_console()
print("clean screen")subprocess로 호출하기
os.system은 간단하지만, 새 코드에서는 subprocess.run을 선호할 수 있다. 외부 입력을 명령 문자열에 직접 섞지 않는 것이 중요하다.
import os
import subprocess
def clear_console() -> None:
command = "cls" if os.name == "nt" else "clear"
subprocess.run(command, shell=True, check=False)ANSI escape 사용
터미널이 ANSI escape sequence를 지원하면 외부 명령 없이 화면을 지울 수 있다. 다만 오래된 Windows 콘솔이나 일부 IDE 콘솔에서는 기대한 대로 동작하지 않을 수 있다.
def clear_with_ansi() -> None:
print("\033[2J\033[H", end="")메뉴 프로그램 예제
import os
def clear_console() -> None:
os.system("cls" if os.name == "nt" else "clear")
def show_menu() -> None:
clear_console()
print("1. List posts")
print("2. Create post")
print("3. Exit")
while True:
show_menu()
choice = input("select> ").strip()
if choice == "3":
break
input("Enter를 누르면 메뉴로 돌아갑니다.")주의할 점
- 화면을 지우는 것은 출력 표시만 정리할 뿐, 로그를 삭제하는 기능이 아니다.
- 디버깅 중에는 화면을 지우면 이전 출력 확인이 어려울 수 있다.
- IDE 콘솔, Jupyter Notebook, 일반 터미널은 동작 방식이 다를 수 있다.
- 외부 입력을 shell 명령에 직접 넣지 않는다.