programing

파이썬에서 경고가 예외인 것처럼 포착하려면 어떻게 해야 합니까?

jooyons 2023. 6. 14. 21:51
반응형

파이썬에서 경고가 예외인 것처럼 포착하려면 어떻게 해야 합니까?

내 파이썬 코드에서 사용하는 타사 라이브러리(C로 작성)가 경고를 보내고 있습니다.나는 그것을 사용할 수 있기를 원합니다.try except이러한 경고를 적절하게 처리하기 위한 구문입니다.이것을 할 수 있는 방법이 있습니까?

경고를 오류로 처리하려면 다음을 사용합니다.

import warnings
warnings.filterwarnings("error")

이 후에는 오류와 같은 경고를 수신할 수 있습니다. 예를 들어 다음과 같은 경고가 작동합니다.

try:
    some_heavy_calculations()
except RuntimeWarning:
    breakpoint()

다음을 실행하여 경고 동작을 재설정할 수도 있습니다.

warnings.resetwarnings()

추신. 댓글 중 가장 좋은 답변에 맞춤법 오류가 포함되어 있기 때문에 이 답변을 추가했습니다.filterwarnigns대신에filterwarnings.

파이썬 핸드북(27.6.4)에서 인용합니다. 테스트 경고):

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)

스크립트가 경고에 실패하도록 하려면 호출할 수 있습니다.python다음과 같은 인수를 사용합니다.

python -W error foobar.py

다음은 사용자 지정 경고만 사용하여 작업하는 방법을 명확히 하는 변형입니다.

import warnings
with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")

    # Call some code that triggers a custom warning.
    functionThatRaisesWarning()

    # ignore any non-custom warnings that may be in the list
    w = filter(lambda i: issubclass(i.category, UserWarning), w)

    if len(w):
        # do something with the first warning
        email_admins(w[0].message)

niekas 답변을 확장하지만, 사용합니다.catch_warnings컨텍스트 종료 후 경고 동작을 기본값으로 재설정하는 컨텍스트 관리자:

import warnings

with warnings.catch_warnings():
     warnings.simplefilter("error")
     # Code in this block will raise exception for a warning
# Code in this block will have default warning behaviour

경우에 따라 ctypes를 사용하여 경고를 오류로 전환해야 합니다.예:

str(b'test')  # no error
import warnings
warnings.simplefilter('error', BytesWarning)
str(b'test')  # still no error
import ctypes
ctypes.c_int.in_dll(ctypes.pythonapi, 'Py_BytesWarningFlag').value = 2
str(b'test')  # this raises an error

모든 경고를 잡는 것은 문제가 될 수 있습니다.특정 경고를 잡을 수 있습니다.예를 들어 베개 경고를 받아야 했습니다.

import warnings
warnings.filterwarnings("error", category=Image.DecompressionBombWarning)

def process_images():
  try:
    some_process()

  except Image.DecompressionBombWarning as e:
    print(e)

완전성을 위해 env 변수를 내보낼 수도 있습니다.

PYTHONWARNINGS=error /usr/bin/run_my_python_utility

언급URL : https://stackoverflow.com/questions/5644836/in-python-how-does-one-catch-warnings-as-if-they-were-exceptions

반응형