예외 처리

The functions described in this chapter will let you handle and raise Python exceptions. It is important to understand some of the basics of Python exception handling. It works somewhat like the POSIX errno variable: there is a global indicator (per thread) of the last error that occurred. Most C API functions don’t clear this on success, but will set it to indicate the cause of the error on failure. Most C API functions also return an error indicator, usually NULL if they are supposed to return a pointer, or -1 if they return an integer (exception: the PyArg_* functions return 1 for success and 0 for failure).

구체적으로, 에러 표시기는 세 가지 객체 포인터로 구성됩니다: 예외 형, 예외 값 및 트레이스백 객체. 이러한 포인터들은 설정되지 않으면 NULL이 될 수 있습니다 (하지만 일부 조합은 금지되어 있습니다, 예를 들어 예외 형이 NULL이면 NULL이 아닌 트레이스백을 가질 수 없습니다).

호출한 일부 함수가 실패하여 함수가 실패해야 할 때, 일반적으로 에러 표시기를 설정하지 않습니다; 호출된 함수가 이미 설정했습니다. 에러를 처리하고 예외를 지우거나 보유한 모든 리소스(가령 객체 참조나 메모리 할당)를 정리한 후 반환해야 할 책임이 있습니다; 에러를 처리할 준비가 되지 않았을 때 정상적으로 계속되지 않아야 합니다. 에러로 인해 반환하면, 호출자에게 에러가 설정되었음을 알리는 것이 중요합니다. 에러를 처리하지 않거나 신중하게 전파하지 않으면, 파이썬/C API에 대한 추가 호출이 의도한 대로 작동하지 않을 수 있으며 알 수 없는 방식으로 실패할 수 있습니다.

참고

에러 표시기는 sys.exc_info()의 결과가 아닙니다. 전자는 아직 포착되지 않은 (따라서 여전히 전파 중인) 예외에 해당하는 반면, 후자는 포착된 후 (따라서 전파가 중단된) 예외를 반환합니다.

인쇄와 지우기

void PyErr_Clear()
Part of the Stable ABI.

에러 표시기를 지웁니다. 에러 표시기가 설정되어 있지 않으면 효과가 없습니다.

void PyErr_PrintEx(int set_sys_last_vars)
Part of the Stable ABI.

표준 트레이스백을 sys.stderr로 인쇄하고 에러 표시기를 지웁니다. 에러가 SystemExit아닌 한, 이 경우에는 트레이스백이 인쇄되지 않고 파이썬 프로세스는 SystemExit 인스턴스에 의해 지정된 에러 코드로 종료됩니다.

에러 표시기가 설정된 경우**에만** 이 함수를 호출하십시오. 그렇지 않으면 치명적인 에러가 발생합니다!

If set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For backwards compatibility, the deprecated variables sys.last_type, sys.last_value and sys.last_traceback are also set to the type, value and traceback of this exception, respectively.

버전 3.12에서 변경: The setting of sys.last_exc was added.

void PyErr_Print()
Part of the Stable ABI.

PyErr_PrintEx(1)의 별칭.

void PyErr_WriteUnraisable(PyObject *obj)
Part of the Stable ABI.

현재 예외와 obj 인자를 사용하여 sys.unraisablehook() 을 호출합니다.

This utility function prints a warning message to sys.stderr when an exception has been set but it is impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs in an __del__() method.

The function is called with a single argument obj that identifies the context in which the unraisable exception occurred. If possible, the repr of obj will be printed in the warning message. If obj is NULL, only the traceback is printed.

이 함수를 호출할 때 예외를 설정되어 있어야 합니다.

버전 3.4에서 변경: Print a traceback. Print only traceback if obj is NULL.

버전 3.8에서 변경: Use sys.unraisablehook().

void PyErr_DisplayException(PyObject *exc)
Part of the Stable ABI since version 3.12.

Print the standard traceback display of exc to sys.stderr, including chained exceptions and notes.

버전 3.12에 추가.

예외 발생시키기

이 함수들은 현재 스레드의 에러 표시기를 설정하는 데 도움이 됩니다. 편의를 위해, 이러한 함수 중 일부는 항상 return 문에서 사용할 NULL 포인터를 반환합니다.

void PyErr_SetString(PyObject *type, const char *message)
Part of the Stable ABI.

This is the most common way to set the error indicator. The first argument specifies the exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not create a new strong reference to it (e.g. with Py_INCREF()). The second argument is an error message; it is decoded from 'utf-8'.

void PyErr_SetObject(PyObject *type, PyObject *value)
Part of the Stable ABI.

이 함수는 PyErr_SetString()과 유사하지만, 예외의 “값”에 대해 임의의 파이썬 객체를 지정할 수 있습니다.

PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
Return value: Always NULL. Part of the Stable ABI.

이 함수는 에러 표시기를 설정하고 NULL을 반환합니다. exception은 파이썬 예외 클래스여야 합니다. format과 후속 매개 변수는 에러 메시지를 포맷하는 데 도움이 됩니다; PyUnicode_FromFormat()에서와 같은 의미와 값을 갖습니다. format은 ASCII 인코딩된 문자열입니다.

PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Return value: Always NULL. Part of the Stable ABI since version 3.5.

PyErr_Format()과 같지만, 가변 개수의 인자 대신 va_list 인자를 취합니다.

버전 3.5에 추가.

void PyErr_SetNone(PyObject *type)
Part of the Stable ABI.

이것은 PyErr_SetObject(type, Py_None)의 줄임 표현입니다.

int PyErr_BadArgument()
Part of the Stable ABI.

이것은 PyErr_SetString(PyExc_TypeError, message)의 줄임 표현입니다, 여기서 message는 잘못된 인자로 내장 연산이 호출되었음을 나타냅니다. 대부분 내부 용입니다.

PyObject *PyErr_NoMemory()
Return value: Always NULL. Part of the Stable ABI.

이것은 PyErr_SetNone(PyExc_MemoryError)의 줄임 표현입니다; NULL을 반환해서 객체 할당 함수는 메모리가 부족할 때 return PyErr_NoMemory(); 라고 쓸 수 있습니다.

PyObject *PyErr_SetFromErrno(PyObject *type)
Return value: Always NULL. Part of the Stable ABI.

This is a convenience function to raise an exception when a C library function has returned an error and set the C variable errno. It constructs a tuple object whose first item is the integer errno value and whose second item is the corresponding error message (gotten from strerror()), and then calls PyErr_SetObject(type, object). On Unix, when the errno value is EINTR, indicating an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returns NULL, so a wrapper function around a system call can write return PyErr_SetFromErrno(type); when the system call returns an error.

PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Return value: Always NULL. Part of the Stable ABI.

Similar to PyErr_SetFromErrno(), with the additional behavior that if filenameObject is not NULL, it is passed to the constructor of type as a third parameter. In the case of OSError exception, this is used to define the filename attribute of the exception instance.

PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
Return value: Always NULL. Part of the Stable ABI since version 3.7.

PyErr_SetFromErrnoWithFilenameObject()와 유사하지만, 두 개의 파일명을 취하는 함수가 실패할 때 에러를 발생시키기 위해 두 번째 파일명 객체를 취합니다.

버전 3.4에 추가.

PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
Return value: Always NULL. Part of the Stable ABI.

Similar to PyErr_SetFromErrnoWithFilenameObject(), but the filename is given as a C string. filename is decoded from the filesystem encoding and error handler.

PyObject *PyErr_SetFromWindowsErr(int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.

This is a convenience function to raise OSError. If called with ierr of 0, the error code returned by a call to GetLastError() is used instead. It calls the Win32 function FormatMessage() to retrieve the Windows description of error code given by ierr or GetLastError(), then it constructs a OSError object with the winerror attribute set to the error code, the strerror attribute set to the corresponding error message (gotten from FormatMessage()), and then calls PyErr_SetObject(PyExc_OSError, object). This function always returns NULL.

가용성: 윈도우.

PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.

PyErr_SetFromWindowsErr() 와 유사하며, 발생시킬 예외 형을 지정하는 추가 매개 변수가 있습니다.

가용성: 윈도우.

PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.

Similar to PyErr_SetFromWindowsErr(), with the additional behavior that if filename is not NULL, it is decoded from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third parameter to be used to define the filename attribute of the exception instance.

가용성: 윈도우.

PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.

Similar to PyErr_SetExcFromWindowsErr(), with the additional behavior that if filename is not NULL, it is passed to the constructor of OSError as a third parameter to be used to define the filename attribute of the exception instance.

가용성: 윈도우.

PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.

PyErr_SetExcFromWindowsErrWithFilenameObject()와 유사하지만, 두 번째 파일명 객체를 받아들입니다.

가용성: 윈도우.

버전 3.4에 추가.

PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.

PyErr_SetFromWindowsErrWithFilename()와 유사하며, 발생시킬 예외 형을 지정하는 추가 매개 변수가 있습니다.

가용성: 윈도우.

PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.7.

ImportError를 발생시키는 편의 함수입니다. msg는 예외의 메시지 문자열로 설정됩니다. 둘 다 NULL이 될 수 있는, namepath는 각각 ImportErrornamepath 어트리뷰트로 설정됩니다.

버전 3.3에 추가.

PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.6.

PyErr_SetImportError() 와 매우 비슷하지만, 이 함수는 발생시킬 ImportError의 서브 클래스를 지정할 수 있습니다.

버전 3.6에 추가.

void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)

현재 예외에 대한 파일(file), 줄(line) 및 오프셋(offset) 정보를 설정합니다. 현재 예외가 SyntaxError가 아니면, 추가 어트리뷰트를 설정하여, 예외 인쇄 하위 시스템이 예외가 SyntaxError라고 생각하게 합니다.

버전 3.4에 추가.

void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Part of the Stable ABI since version 3.7.

Like PyErr_SyntaxLocationObject(), but filename is a byte string decoded from the filesystem encoding and error handler.

버전 3.2에 추가.

void PyErr_SyntaxLocation(const char *filename, int lineno)
Part of the Stable ABI.

Like PyErr_SyntaxLocationEx(), but the col_offset parameter is omitted.

void PyErr_BadInternalCall()
Part of the Stable ABI.

이것은 PyErr_SetString(PyExc_SystemError, message)의 줄임 표현입니다. 여기서 message는 내부 연산(예를 들어 파이썬/C API 함수)이 잘못된 인자로 호출되었음을 나타냅니다. 대부분 내부 용입니다.

경고 발행하기

이 함수를 사용하여 C 코드에서 경고를 발행하십시오. 파이썬 warnings 모듈에서 내보낸 유사한 함수를 미러링합니다. 일반적으로 sys.stderr에 경고 메시지를 인쇄합니다; 그러나, 사용자가 경고를 에러로 전환하도록 지정했을 수도 있으며, 이 경우 예외가 발생합니다. 경고 장치의 문제로 인해 이 함수가 예외를 발생시키는 것도 가능합니다. 예외가 발생하지 않으면 반환 값은 0이고, 예외가 발생하면 -1입니다. (경고 메시지가 실제로 인쇄되는지나 예외의 이유를 확인할 수 없습니다; 이것은 의도적입니다.) 예외가 발생하면, 호출자는 정상적인 예외 처리를 수행해야 합니다 (예를 들어, 소유한 참조를 Py_DECREF()하고 에러값을 반환합니다).

int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Part of the Stable ABI.

경고 메시지를 발행합니다. category 인자는 경고 범주(아래를 참조하십시오)나 NULL입니다; message 인자는 UTF-8로 인코딩된 문자열입니다. stack_level은 스택 프레임 수를 제공하는 양수입니다; 해당 스택 프레임에서 현재 실행 중인 코드 줄에서 경고가 발생합니다. stack_level이 1이면 PyErr_WarnEx()를 호출하는 함수, 2는 그 위의 함수, 등등.

경고 범주는 PyExc_Warning의 서브 클래스여야 합니다. PyExc_WarningPyExc_Exception의 서브 클래스입니다; 기본 경고 범주는 PyExc_RuntimeWarning입니다. 표준 파이썬 경고 범주는 이름이 표준 경고 범주 에 열거된 전역 변수로 제공됩니다.

경고 제어에 대한 자세한 내용은, warnings 모듈 설명서와 명령 줄 설명서에서 -W 옵션을 참조하십시오. 경고 제어를 위한 C API는 없습니다.

int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)

Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper around the Python function warnings.warn_explicit(); see there for more information. The module and registry arguments may be set to NULL to get the default effect described there.

버전 3.4에 추가.

int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
Part of the Stable ABI.

Similar to PyErr_WarnExplicitObject() except that message and module are UTF-8 encoded strings, and filename is decoded from the filesystem encoding and error handler.

int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI.

PyErr_WarnEx()와 유사한 함수지만, PyUnicode_FromFormat()을 사용하여 경고 메시지를 포맷합니다. format은 ASCII 인코딩된 문자열입니다.

버전 3.2에 추가.

int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI since version 3.6.

Function similar to PyErr_WarnFormat(), but category is ResourceWarning and it passes source to warnings.WarningMessage.

버전 3.6에 추가.

에러 표시기 조회하기

PyObject *PyErr_Occurred()
Return value: Borrowed reference. Part of the Stable ABI.

Test whether the error indicator is set. If set, return the exception type (the first argument to the last call to one of the PyErr_Set* functions or to PyErr_Restore()). If not set, return NULL. You do not own a reference to the return value, so you do not need to Py_DECREF() it.

호출자는 GIL을 보유해야 합니다.

참고

반환 값을 특정 예외와 비교하지 마십시오; 대신 PyErr_ExceptionMatches()를 사용하십시오, 아래를 참조하십시오. (클래스 예외의 경우 예외가 클래스 대신 인스턴스이거나, 예상하는 예외의 서브 클래스일 수 있어서 비교는 실패하기 쉽습니다.)

int PyErr_ExceptionMatches(PyObject *exc)
Part of the Stable ABI.

PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)와 동등합니다. 예외가 실제로 설정되었을 때만 호출해야 합니다; 예외가 발생하지 않았으면 메모리 액세스 위반이 발생합니다.

int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
Part of the Stable ABI.

given 예외가 exc의 예외 형과 일치하면 참을 반환합니다. exc가 클래스 객체이면, given이 서브 클래스의 인스턴스일 때도 참을 반환합니다. exc가 튜플이면, 튜플에 있는 모든 예외 형(그리고 서브 튜플도 재귀적으로)을 일치를 위해 검색합니다.

PyObject *PyErr_GetRaisedException(void)
Return value: New reference. Part of the Stable ABI since version 3.12.

Return the exception currently being raised, clearing the error indicator at the same time. Return NULL if the error indicator is not set.

This function is used by code that needs to catch exceptions, or code that needs to save and restore the error indicator temporarily.

For example:

{
   PyObject *exc = PyErr_GetRaisedException();

   /* ... code that might produce other errors ... */

   PyErr_SetRaisedException(exc);
}

더 보기

PyErr_GetHandledException(), to save the exception currently being handled.

버전 3.12에 추가.

void PyErr_SetRaisedException(PyObject *exc)
Part of the Stable ABI since version 3.12.

Set exc as the exception currently being raised, clearing the existing exception if one is set.

경고

This call steals a reference to exc, which must be a valid exception.

버전 3.12에 추가.

void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
Part of the Stable ABI.

버전 3.12부터 폐지됨: Use PyErr_GetRaisedException() instead.

주소가 전달된 세 개의 변수로 에러 표시기를 꺼냅니다. 에러 표시기가 설정되지 않았으면, 세 변수를 모두 NULL로 설정합니다. 설정되었으면, 지워지고 꺼낸 각 객체에 대한 참조를 여러분이 소유합니다. 값과 트레이스백 객체는 형 객체가 그렇지 않을 때도 NULL일 수 있습니다.

참고

This function is normally only used by legacy code that needs to catch exceptions or save and restore the error indicator temporarily.

For example:

{
   PyObject *type, *value, *traceback;
   PyErr_Fetch(&type, &value, &traceback);

   /* ... code that might produce other errors ... */

   PyErr_Restore(type, value, traceback);
}
void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Part of the Stable ABI.

버전 3.12부터 폐지됨: Use PyErr_SetRaisedException() instead.

Set the error indicator from the three objects, type, value, and traceback, clearing the existing exception if one is set. If the objects are NULL, the error indicator is cleared. Do not pass a NULL type and non-NULL value or traceback. The exception type should be a class. Do not pass an invalid exception type or value. (Violating these rules will cause subtle problems later.) This call takes away a reference to each object: you must own a reference to each object before the call and after the call you no longer own these references. (If you don’t understand this, don’t use this function. I warned you.)

참고

This function is normally only used by legacy code that needs to save and restore the error indicator temporarily. Use PyErr_Fetch() to save the current error indicator.

void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Part of the Stable ABI.

버전 3.12부터 폐지됨: Use PyErr_GetRaisedException() instead, to avoid any possible de-normalization.

특정 상황에서, 아래의 PyErr_Fetch()가 반환하는 값은 “비 정규화”되었을 수 있습니다. 즉, *exc는 클래스 객체이지만 *val은 같은 클래스의 인스턴스가 아닙니다. 이 함수는 이 경우 클래스를 인스턴스 화하는 데 사용할 수 있습니다. 값이 이미 정규화되어 있으면, 아무 일도 일어나지 않습니다. 지연된 정규화는 성능 향상을 위해 구현됩니다.

참고

This function does not implicitly set the __traceback__ attribute on the exception value. If setting the traceback appropriately is desired, the following additional snippet is needed:

if (tb != NULL) {
  PyException_SetTraceback(val, tb);
}
PyObject *PyErr_GetHandledException(void)
Part of the Stable ABI since version 3.11.

Retrieve the active exception instance, as would be returned by sys.exception(). This refers to an exception that was already caught, not to an exception that was freshly raised. Returns a new reference to the exception or NULL. Does not modify the interpreter’s exception state.

참고

This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use PyErr_SetHandledException() to restore or clear the exception state.

버전 3.11에 추가.

void PyErr_SetHandledException(PyObject *exc)
Part of the Stable ABI since version 3.11.

Set the active exception, as known from sys.exception(). This refers to an exception that was already caught, not to an exception that was freshly raised. To clear the exception state, pass NULL.

참고

This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use PyErr_GetHandledException() to get the exception state.

버전 3.11에 추가.

void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
Part of the Stable ABI since version 3.7.

Retrieve the old-style representation of the exception info, as known from sys.exc_info(). This refers to an exception that was already caught, not to an exception that was freshly raised. Returns new references for the three objects, any of which may be NULL. Does not modify the exception info state. This function is kept for backwards compatibility. Prefer using PyErr_GetHandledException().

참고

이 함수는 일반적으로 예외를 처리하려는 코드에서 사용되지 않습니다. 오히려, 코드가 예외 상태를 임시로 저장하고 복원해야 할 때 사용할 수 있습니다. 예외 상태를 복원하거나 지우려면 PyErr_SetExcInfo()를 사용하십시오.

버전 3.3에 추가.

void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
Part of the Stable ABI since version 3.7.

Set the exception info, as known from sys.exc_info(). This refers to an exception that was already caught, not to an exception that was freshly raised. This function steals the references of the arguments. To clear the exception state, pass NULL for all three arguments. This function is kept for backwards compatibility. Prefer using PyErr_SetHandledException().

참고

이 함수는 일반적으로 예외를 처리하려는 코드에서 사용되지 않습니다. 오히려, 코드가 예외 상태를 임시로 저장하고 복원해야 할 때 사용할 수 있습니다. 예외 상태를 읽으려면 PyErr_GetExcInfo()를 사용하십시오.

버전 3.3에 추가.

버전 3.11에서 변경: The type and traceback arguments are no longer used and can be NULL. The interpreter now derives them from the exception instance (the value argument). The function still steals references of all three arguments.

시그널 처리하기

int PyErr_CheckSignals()
Part of the Stable ABI.

This function interacts with Python’s signal handling.

If the function is called from the main thread and under the main Python interpreter, it checks whether a signal has been sent to the processes and if so, invokes the corresponding signal handler. If the signal module is supported, this can invoke a signal handler written in Python.

The function attempts to handle all pending signals, and then returns 0. However, if a Python signal handler raises an exception, the error indicator is set and the function returns -1 immediately (such that other pending signals may not have been handled yet: they will be on the next PyErr_CheckSignals() invocation).

If the function is called from a non-main thread, or under a non-main Python interpreter, it does nothing and returns 0.

This function can be called by long-running C code that wants to be interruptible by user requests (such as by pressing Ctrl-C).

참고

The default Python signal handler for SIGINT raises the KeyboardInterrupt exception.

void PyErr_SetInterrupt()
Part of the Stable ABI.

Simulate the effect of a SIGINT signal arriving. This is equivalent to PyErr_SetInterruptEx(SIGINT).

참고

This function is async-signal-safe. It can be called without the GIL and from a C signal handler.

int PyErr_SetInterruptEx(int signum)
Part of the Stable ABI since version 3.10.

Simulate the effect of a signal arriving. The next time PyErr_CheckSignals() is called, the Python signal handler for the given signal number will be called.

This function can be called by C code that sets up its own signal handling and wants Python signal handlers to be invoked as expected when an interruption is requested (for example when the user presses Ctrl-C to interrupt an operation).

If the given signal isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), it will be ignored.

If signum is outside of the allowed range of signal numbers, -1 is returned. Otherwise, 0 is returned. The error indicator is never changed by this function.

참고

This function is async-signal-safe. It can be called without the GIL and from a C signal handler.

버전 3.10에 추가.

int PySignal_SetWakeupFd(int fd)

이 유틸리티 함수는 시그널이 수신될 때마다 시그널 번호가 단일 바이트로 기록되는 파일 기술자를 지정합니다. fd는 비 블로킹이어야 합니다. 이전의 파일 기술자를 반환합니다.

-1은 기능을 비활성화합니다; 이것이 초기 상태입니다. 이것은 파이썬의 signal.set_wakeup_fd()와 동등하지만, 에러 검사는 없습니다. fd는 유효한 파일 기술자여야 합니다. 함수는 메인 스레드에서만 호출되어야 합니다.

버전 3.5에서 변경: 윈도우에서, 함수는 이제 소켓 핸들도 지원합니다.

예외 클래스

PyObject *PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Return value: New reference. Part of the Stable ABI.

이 유틸리티 함수는 새 예외 클래스를 만들고 반환합니다. name 인자는 새 예외의 이름, module.classname 형식의 C 문자열이어야 합니다. basedict 인자는 일반적으로 NULL입니다. 이렇게 하면 Exception(C에서 PyExc_Exception으로 액세스할 수 있습니다)에서 파생된 클래스 객체가 만들어집니다.

The __module__ attribute of the new class is set to the first part (up to the last dot) of the name argument, and the class name is set to the last part (after the last dot). The base argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes. The dict argument can be used to specify a dictionary of class variables and methods.

PyObject *PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
Return value: New reference. Part of the Stable ABI.

새로운 예외 클래스에 독스트링을 쉽게 부여할 수 있다는 점을 제외하면 PyErr_NewException()과 같습니다: docNULL이 아니면, 예외 클래스에 대한 독스트링으로 사용됩니다.

버전 3.2에 추가.

예외 객체

PyObject *PyException_GetTraceback(PyObject *ex)
Return value: New reference. Part of the Stable ABI.

Return the traceback associated with the exception as a new reference, as accessible from Python through the __traceback__ attribute. If there is no traceback associated, this returns NULL.

int PyException_SetTraceback(PyObject *ex, PyObject *tb)
Part of the Stable ABI.

예외와 관련된 트레이스백을 tb로 설정합니다. 지우려면 Py_None을 사용하십시오.

PyObject *PyException_GetContext(PyObject *ex)
Return value: New reference. Part of the Stable ABI.

Return the context (another exception instance during whose handling ex was raised) associated with the exception as a new reference, as accessible from Python through the __context__ attribute. If there is no context associated, this returns NULL.

void PyException_SetContext(PyObject *ex, PyObject *ctx)
Part of the Stable ABI.

예외와 연관된 컨텍스트를 ctx로 설정합니다. 지우려면 NULL을 사용하십시오. ctx가 예외 인스턴스인지 확인하는 형 검사는 없습니다. 이것은 ctx에 대한 참조를 훔칩니다.

PyObject *PyException_GetCause(PyObject *ex)
Return value: New reference. Part of the Stable ABI.

Return the cause (either an exception instance, or None, set by raise ... from ...) associated with the exception as a new reference, as accessible from Python through the __cause__ attribute.

void PyException_SetCause(PyObject *ex, PyObject *cause)
Part of the Stable ABI.

Set the cause associated with the exception to cause. Use NULL to clear it. There is no type check to make sure that cause is either an exception instance or None. This steals a reference to cause.

The __suppress_context__ attribute is implicitly set to True by this function.

PyObject *PyException_GetArgs(PyObject *ex)
Return value: New reference. Part of the Stable ABI since version 3.12.

Return args of exception ex.

void PyException_SetArgs(PyObject *ex, PyObject *args)
Part of the Stable ABI since version 3.12.

Set args of exception ex to args.

PyObject *PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)
This is Unstable API. It may change without warning in minor releases.

Implement part of the interpreter’s implementation of except*. orig is the original exception that was caught, and excs is the list of the exceptions that need to be raised. This list contains the unhandled part of orig, if any, as well as the exceptions that were raised from the except* clauses (so they have a different traceback from orig) and those that were reraised (and have the same traceback as orig). Return the ExceptionGroup that needs to be reraised in the end, or None if there is nothing to reraise.

버전 3.12에 추가.

유니코드 예외 객체

다음 함수는 C에서 유니코드 예외를 만들고 수정하는 데 사용됩니다.

PyObject *PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
Return value: New reference. Part of the Stable ABI.

encoding, object, length, start, endreason 어트리뷰트를 사용하여 UnicodeDecodeError 객체를 만듭니다. encodingreason은 UTF-8로 인코딩된 문자열입니다.

PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)
Return value: New reference. Part of the Stable ABI.

주어진 예외 객체의 encoding 어트리뷰트를 반환합니다.

PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)
Return value: New reference. Part of the Stable ABI.

주어진 예외 객체의 object 어트리뷰트를 반환합니다.

int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
Part of the Stable ABI.

주어진 예외 객체의 start 어트리뷰트를 가져와서 *start에 배치합니다. startNULL이 아니어야 합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
Part of the Stable ABI.

주어진 예외 객체의 start 어트리뷰트를 start로 설정합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
Part of the Stable ABI.

주어진 예외 객체의 end 어트리뷰트를 가져와서 *end에 배치합니다. endNULL이 아니어야 합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
Part of the Stable ABI.

주어진 예외 객체의 end 어트리뷰트를 end로 설정합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)
Return value: New reference. Part of the Stable ABI.

주어진 예외 객체의 reason 어트리뷰트를 반환합니다.

int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
Part of the Stable ABI.

주어진 예외 객체의 reason 어트리뷰트를 reason으로 설정합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

재귀 제어

이 두 함수는 코어와 확장 모듈 모두에서 C 수준에서 안전한 재귀 호출을 수행하는 방법을 제공합니다. 재귀 코드가 반드시 파이썬 코드를 호출하지 않는 경우 필요합니다 (파이썬 코드는 재귀 깊이를 자동으로 추적합니다). 호출 프로토콜이 재귀 처리를 처리하기 때문에 tp_call 구현에도 필요하지 않습니다.

int Py_EnterRecursiveCall(const char *where)
Part of the Stable ABI since version 3.9.

재귀적 C 수준 호출이 막 수행되려고 하는 지점을 표시합니다.

If USE_STACKCHECK is defined, this function checks if the OS stack overflowed using PyOS_CheckStack(). If this is the case, it sets a MemoryError and returns a nonzero value.

그런 다음 함수는 재귀 제한에 도달했는지 확인합니다. 이 경우, RecursionError가 설정되고 0이 아닌 값이 반환됩니다. 그렇지 않으면, 0이 반환됩니다.

where는 재귀 깊이 제한으로 인한 RecursionError 메시지에 이어붙일 " in instance check"와 같은 UTF-8 인코딩된 문자열이어야 합니다.

버전 3.9에서 변경: This function is now also available in the limited API.

void Py_LeaveRecursiveCall(void)
Part of the Stable ABI since version 3.9.

Py_EnterRecursiveCall() 을 종료합니다. Py_EnterRecursiveCall() 의 각 성공적인 호출마다 한 번씩 호출되어야 합니다.

버전 3.9에서 변경: This function is now also available in the limited API.

컨테이너형에 대해 tp_repr을 올바르게 구현하려면 특별한 재귀 처리가 필요합니다. 스택을 보호하는 것 외에도, tp_repr은 순환을 방지하기 위해 객체를 추적해야 합니다. 다음 두 함수는 이 기능을 쉽게 만듭니다. 사실상, 이들은 reprlib.recursive_repr()에 대한 C 동등물입니다.

int Py_ReprEnter(PyObject *object)
Part of the Stable ABI.

순환을 감지하기 위해 tp_repr 구현 시작 시 호출됩니다.

객체가 이미 처리되었으면, 함수는 양의 정수를 반환합니다. 이 경우 tp_repr 구현은 순환을 나타내는 문자열 객체를 반환해야 합니다. 예를 들어, dict 객체는 {...}를 반환하고 list 객체는 [...]를 반환합니다.

재귀 제한에 도달하면 함수는 음의 정수를 반환합니다. 이 경우 tp_repr 구현은 일반적으로 NULL을 반환해야 합니다.

그렇지 않으면, 함수는 0을 반환하고 tp_repr 구현은 정상적으로 계속될 수 있습니다.

void Py_ReprLeave(PyObject *object)
Part of the Stable ABI.

Py_ReprEnter()를 종료합니다. 0을 반환하는 Py_ReprEnter() 호출마다 한 번씩 호출해야 합니다.

표준 예외

All standard Python exceptions are available as global variables whose names are PyExc_ followed by the Python exception name. These have the type PyObject*; they are all class objects. For completeness, here are all the variables:

C 이름

파이썬 이름

노트

PyExc_BaseException

BaseException

[1]

PyExc_Exception

Exception

[1]

PyExc_ArithmeticError

ArithmeticError

[1]

PyExc_AssertionError

AssertionError

PyExc_AttributeError

AttributeError

PyExc_BlockingIOError

BlockingIOError

PyExc_BrokenPipeError

BrokenPipeError

PyExc_BufferError

BufferError

PyExc_ChildProcessError

ChildProcessError

PyExc_ConnectionAbortedError

ConnectionAbortedError

PyExc_ConnectionError

ConnectionError

PyExc_ConnectionRefusedError

ConnectionRefusedError

PyExc_ConnectionResetError

ConnectionResetError

PyExc_EOFError

EOFError

PyExc_FileExistsError

FileExistsError

PyExc_FileNotFoundError

FileNotFoundError

PyExc_FloatingPointError

FloatingPointError

PyExc_GeneratorExit

GeneratorExit

PyExc_ImportError

ImportError

PyExc_IndentationError

IndentationError

PyExc_IndexError

IndexError

PyExc_InterruptedError

InterruptedError

PyExc_IsADirectoryError

IsADirectoryError

PyExc_KeyError

KeyError

PyExc_KeyboardInterrupt

KeyboardInterrupt

PyExc_LookupError

LookupError

[1]

PyExc_MemoryError

MemoryError

PyExc_ModuleNotFoundError

ModuleNotFoundError

PyExc_NameError

NameError

PyExc_NotADirectoryError

NotADirectoryError

PyExc_NotImplementedError

NotImplementedError

PyExc_OSError

OSError

[1]

PyExc_OverflowError

OverflowError

PyExc_PermissionError

PermissionError

PyExc_ProcessLookupError

ProcessLookupError

PyExc_RecursionError

RecursionError

PyExc_ReferenceError

ReferenceError

PyExc_RuntimeError

RuntimeError

PyExc_StopAsyncIteration

StopAsyncIteration

PyExc_StopIteration

StopIteration

PyExc_SyntaxError

SyntaxError

PyExc_SystemError

SystemError

PyExc_SystemExit

SystemExit

PyExc_TabError

TabError

PyExc_TimeoutError

TimeoutError

PyExc_TypeError

TypeError

PyExc_UnboundLocalError

UnboundLocalError

PyExc_UnicodeDecodeError

UnicodeDecodeError

PyExc_UnicodeEncodeError

UnicodeEncodeError

PyExc_UnicodeError

UnicodeError

PyExc_UnicodeTranslateError

UnicodeTranslateError

PyExc_ValueError

ValueError

PyExc_ZeroDivisionError

ZeroDivisionError

버전 3.3에 추가: PyExc_BlockingIOError, PyExc_BrokenPipeError, PyExc_ChildProcessError, PyExc_ConnectionError, PyExc_ConnectionAbortedError, PyExc_ConnectionRefusedError, PyExc_ConnectionResetError, PyExc_FileExistsError, PyExc_FileNotFoundError, PyExc_InterruptedError, PyExc_IsADirectoryError, PyExc_NotADirectoryError, PyExc_PermissionError, PyExc_ProcessLookupErrorPyExc_TimeoutErrorPEP 3151을 따라 도입되었습니다.

버전 3.5에 추가: PyExc_StopAsyncIterationPyExc_RecursionError.

버전 3.6에 추가: PyExc_ModuleNotFoundError.

다음은 PyExc_OSError에 대한 호환성 별칭입니다:

C 이름

노트

PyExc_EnvironmentError

PyExc_IOError

PyExc_WindowsError

[2]

버전 3.3에서 변경: 이러한 별칭은 별도의 예외 형이었습니다.

노트:

표준 경고 범주

All standard Python warning categories are available as global variables whose names are PyExc_ followed by the Python exception name. These have the type PyObject*; they are all class objects. For completeness, here are all the variables:

C 이름

파이썬 이름

노트

PyExc_Warning

Warning

[3]

PyExc_BytesWarning

BytesWarning

PyExc_DeprecationWarning

DeprecationWarning

PyExc_FutureWarning

FutureWarning

PyExc_ImportWarning

ImportWarning

PyExc_PendingDeprecationWarning

PendingDeprecationWarning

PyExc_ResourceWarning

ResourceWarning

PyExc_RuntimeWarning

RuntimeWarning

PyExc_SyntaxWarning

SyntaxWarning

PyExc_UnicodeWarning

UnicodeWarning

PyExc_UserWarning

UserWarning

버전 3.2에 추가: PyExc_ResourceWarning.

노트: