콘텐츠로 이동
Search

Python:warnings

lastmod 2026-11-10created 2021-04-243 edits

Python:warnings는 Python 표준 라이브러리의 warnings 모듈을 정리한 문서이다. 이 모듈은 예외처럼 실행을 멈추지 않고 사용 중단(DeprecationWarning)이나 잠재적 문제를 알리는 경고를 발생시키고 제어하며, warnings.warn()으로 경고를 내고 filterwarnings()나 -W 옵션으로 무시·출력·예외 전환을 지정한다. catch_warnings 컨텍스트 매니저는 블록 안에서 발생한 경고를 가로채 기록하므로 테스트나 로깅에 쓴다.

catch_warnings

경고를 캡쳐할 수 있다.

from io import StringIO
from warnings import catch_warnings

import pygame

verbose = 1
logger = getLogger("test")
size = 1920, 1080
flags = pygame.DOUBLEBUF | pygame.OPENGL | pygame.FULLSCREEN

with catch_warnings(record=True) as wms:
    # [Warning]
    # PyGame seems to be running through X11 on top of wayland,
    # instead of wayland directly `pygame.display.set_mode(size, flags)`
    pygame.display.set_mode(size, flags)

    for wm in wms:
        buffer = StringIO()
        if verbose >= 1:
            buffer.write(f"<{wm.category.__name__} ")
            buffer.write(f"message='{str(wm.message)}' ")
            buffer.write(f"file={wm.filename}:{wm.lineno}>")
        else:
            buffer.write(f"{str(wm.message)}")
        logger.warning(buffer.getvalue())

See also

Favorite site

author Zer0, MCPBot sitemap