Operating System Utilities
Return the file system representation for path. If the object is a
strorbytesobject, then a newstrong referenceis returned. If the object implements theos.PathLikeinterface, then~os.PathLike.__fspath__is returned as long as it is astrorbytesobject. OtherwiseTypeErroris raised andNULLis returned.3.6
Return true (nonzero) if the standard I/O file fp with name filename is deemed interactive. This is the case for files for which
isatty(fileno(fp))is true. If thePyConfig.interactiveis non-zero, this function also returns true if the filename pointer isNULLor if the name is equal to one of the strings'<stdin>'or'???'.This function must not be called before Python is initialized.
Function to prepare some internal state before a process fork. This should be called before calling
forkor any similar function that clones the current process. Only available on systems whereforkis defined.[!WARNING] The C
forkcall should only be made from the"main" thread <fork-and-threads>(of the"main" interpreter <sub-interpreter-support>). The same is true forPyOS_BeforeFork().3.7
Function to update some internal state after a process fork. This should be called from the parent process after calling
forkor any similar function that clones the current process, regardless of whether process cloning was successful. Only available on systems whereforkis defined.[!WARNING] The C
forkcall should only be made from the"main" thread <fork-and-threads>(of the"main" interpreter <sub-interpreter-support>). The same is true forPyOS_AfterFork_Parent().3.7
Function to update internal interpreter state after a process fork. This must be called from the child process after calling
fork, or any similar function that clones the current process, if there is any chance the process will call back into the Python interpreter. Only available on systems whereforkis defined.[!WARNING] The C
forkcall should only be made from the"main" thread <fork-and-threads>(of the"main" interpreter <sub-interpreter-support>). The same is true forPyOS_AfterFork_Child().3.7
os.register_at_forkallows registering custom Python functions to be called byPyOS_BeforeFork(),PyOS_AfterFork_ParentandPyOS_AfterFork_Child.
Function to update some internal state after a process fork; this should be called in the new process if the Python interpreter will continue to be used. If a new executable is loaded into the new process, this function does not need to be called.
3.7 This function is superseded by
PyOS_AfterFork_Child().
single: USE_STACKCHECK (C macro)
Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when
!USE_STACKCHECKis defined (currently on certain versions of Windows using the Microsoft Visual C++ compiler).!USE_STACKCHECKwill be defined automatically; you should never change the definition in your own code.
Return the current signal handler for signal i. This is a thin wrapper around either
!sigactionor!signal. Do not call those functions directly!
Set the signal handler for signal i to be h; return the old signal handler. This is a thin wrapper around either
!sigactionor!signal. Do not call those functions directly!
Check if a
!SIGINTsignal has been received.Returns
1if a!SIGINThas occurred and clears the signal flag, or0otherwise.In most cases, you should prefer
PyErr_CheckSignalsover this function.!PyErr_CheckSignalsinvokes the appropriate signal handlers for all pending signals, allowing Python code to handle the signal properly. This function only detects!SIGINTand does not invoke any Python signal handlers.This function is async-signal-safe and this function cannot fail. The caller must hold an
attached thread state.
[!WARNING] This function should not be called directly: use the
PyConfigAPI with thePyConfig_SetBytesStringfunction which ensures thatPython is preinitialized <c-preinit>.This function must not be called before
Python is preinitialized <c-preinit>and so that the LC_CTYPE locale is properly configured: see thePy_PreInitializefunction.Decode a byte string from the
filesystem encoding <filesystem encoding and error handler>with thesurrogateescape error handler <surrogateescape>.Undecodable bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate character, escape the bytes using the surrogateescape error handler instead of decoding them.
Return a pointer to a newly allocated wide character string, use
PyMem_RawFreeto free the memory. If size is notNULL, write the number of wide characters excluding the null character into*sizeOn memory allocation failure, set *size to
(size_t)-1and returnNULL.On decode error, set *size to
(size_t)-2and returnNULL. Decoding errors should never happen, unless there is a bug in the C library.The
filesystem encoding and error handlerare selected byPyConfig_Read: see~PyConfig.filesystem_encodingand~PyConfig.filesystem_errorsmembers ofPyConfig.Use the
Py_EncodeLocalefunction to encode the character string back to a byte string.The
PyUnicode_DecodeFSDefaultAndSizeandPyUnicode_DecodeLocaleAndSizefunctions.3.5
3.7 The function now uses the UTF-8 encoding in the
Python UTF-8 Mode <utf8-mode>.3.8 The function now uses the UTF-8 encoding on Windows if
PyPreConfig.legacy_windows_fs_encodingis zero;
Encode a wide character string to the
filesystem encoding <filesystem encoding and error handler>with thesurrogateescape error handler <surrogateescape>. Surrogate characters in the range U+DC80..U+DCFF are encoded to bytes 0x80..0xFF.Return a pointer to a newly allocated byte string, use
PyMem_Freeto free the memory.On memory allocation failure, set *error_pos to
(size_t)-1and returnNULL.On encoding error, set *error_pos to the index of the first unencodable character and return
NULL.The
filesystem encoding and error handlerare selected byPyConfig_Read: see~PyConfig.filesystem_encodingand~PyConfig.filesystem_errorsmembers ofPyConfig.Use the
Py_DecodeLocalefunction to decode the bytes string back to a wide character string.[!WARNING] This function must not be called before
Python is preinitialized <c-preinit>and so that the LC_CTYPE locale is properly configured: see thePy_PreInitializefunction.The
PyUnicode_EncodeFSDefaultandPyUnicode_EncodeLocalefunctions.3.5
3.7 The function now uses the UTF-8 encoding in the
Python UTF-8 Mode <utf8-mode>.3.8 The function now uses the UTF-8 encoding on Windows if
PyPreConfig.legacy_windows_fs_encodingis zero.
Similar to
!fopen, but path is a Python object and an exception is set on error.path must be a
strobject, abytesobject, or apath-like object.On success, return the new file pointer. On error, set an exception and return
NULL.The file must be closed by
Py_fcloserather than calling directly!fclose.The file descriptor is created non-inheritable (
446).The caller must have an
attached thread state.3.14
Close a file that was opened by
Py_fopen.On success, return
0. On error, returnEOFanderrnois set to indicate the error. In either case, any further access (including another call toPy_fclose) to the stream results in undefined behavior.3.14
System Functions
These are utility functions that make functionality from the sys module accessible to C code. They all work with the current interpreter thread's sys module's dict, which is contained in the internal thread state structure.
Get the attribute name of the
sysmodule. Return astrong reference. RaiseRuntimeErrorand returnNULLif it does not exist or if thesysmodule cannot be found.If the non-existing object should not be treated as a failure, you can use
PySys_GetOptionalAttrinstead.3.15
This is the same as
PySys_GetAttr, but name is specified as aconst char*UTF-8 encoded bytes string, rather than aPyObject*.If the non-existing object should not be treated as a failure, you can use
PySys_GetOptionalAttrStringinstead.3.15
Variant of
PySys_GetAttrwhich doesn't raise exception if the object does not exist.
- Set *result to a new
strong referenceto the object and return1if the object exists.- Set *result to
NULLand return0without setting an exception if the object does not exist.- Set an exception, set *result to
NULL, and return-1, if an error occurred.3.15
This is the same as
PySys_GetOptionalAttr, but name is specified as aconst char*UTF-8 encoded bytes string, rather than aPyObject*.3.15
Similar to
PySys_GetAttrString, but return aborrowed referenceand returnNULLwithout setting exception on failure.Preserves exception that was set before the call.
Set name in the
sysmodule to v unless v isNULL, in which case name is deleted from the sys module. Returns0on success,-1on error.
Write the output string described by format to
sys.stdout. No exceptions are raised, even if truncation occurs (see below).format should limit the total size of the formatted output string to 1000 bytes or less -- after 1000 bytes, the output string is truncated. In particular, this means that no unrestricted "%s" formats should occur; these should be limited using "%.<N>s" where <N> is a decimal number calculated so that <N> plus the maximum size of other formatted text does not exceed 1000 bytes. Also watch out for "%f", which can print hundreds of digits for very large numbers.
If a problem occurs, or
sys.stdoutis unset, the formatted message is written to the real (C level) stdout.
As
PySys_WriteStdout, but write tosys.stderror stderr instead.
Function similar to PySys_WriteStdout() but format the message using
PyUnicode_FromFormatVand don't truncate the message to an arbitrary length.3.2
As
PySys_FormatStdout, but write tosys.stderror stderr instead.3.2
Return the current dictionary of
-Xoptions, similarly tosys._xoptions. On error,NULLis returned and an exception is set.3.2
Raise an auditing event with any active hooks. Return zero for success and non-zero with an exception set on failure.
The event string argument must not be NULL.
If any hooks have been added, format and other arguments will be used to construct a tuple to pass. Apart from
N, the same format characters as used inPy_BuildValueare available. If the built value is not a tuple, it will be added into a single-element tuple.The
Nformat option must not be used. It consumes a reference, but since there is no way to know whether arguments to this function will be consumed, using it may cause reference leaks.Note that
#format characters should always be treated asPy_ssize_t, regardless of whetherPY_SSIZE_T_CLEANwas defined.
sys.auditperforms the same function from Python code.See also
PySys_AuditTuple.3.8
3.8.2
Require
Py_ssize_tfor#format characters. Previously, an unavoidable deprecation warning was raised.
Similar to
PySys_Audit, but pass arguments as a Python object. args must be atuple. To pass no arguments, args can be NULL.3.13
Append the callable hook to the list of active auditing hooks. Return zero on success and non-zero on failure. If the runtime has been initialized, also set an error on failure. Hooks added through this API are called for all interpreters created by the runtime.
The userData pointer is passed into the hook function. Since hook functions may be called from different runtimes, this pointer should not refer directly to Python state.
This function is safe to call before
Py_Initialize. When called after runtime initialization, existing audit hooks are notified and may silently abort the operation by raising an error subclassed fromRuntimeError(other errors will not be silenced).The hook function is always called with an
attached thread stateby the Python interpreter that raised the event.See
578for a detailed description of auditing. Functions in the runtime and standard library that raise events are listed in theaudit events table <audit-events>. Details are in each function's documentation.sys.addaudithook "" c.PySys_AddAuditHook
If the interpreter is initialized, this function raises an auditing event
sys.addaudithookwith no arguments. If any existing hooks raise an exception derived fromRuntimeError, the new hook will not be added and the exception is cleared. As a result, callers cannot assume that their hook has been added unless they control all existing hooks.The type of the hook function. event is the C string event argument passed to
PySys_AuditorPySys_AuditTuple. args is guaranteed to be aPyTupleObject. userData is the argument passed to PySys_AddAuditHook().3.8
3.8.1
Exceptions derived from
Exceptionbut notRuntimeErrorare no longer suppressed.
Process Control
single: abort (C function)
Print a fatal error message and kill the process. No cleanup is performed. This function should only be invoked when a condition is detected that would make it dangerous to continue using the Python interpreter; e.g., when the object administration appears to be corrupted. On Unix, the standard C library function
!abortis called which will attempt to produce acorefile.The
Py_FatalError()function is replaced with a macro which logs automatically the name of the current function, unless thePy_LIMITED_APImacro is defined.3.9 Log the function name automatically.
single: Py_FinalizeEx (C function) single: exit (C function)
Exit the current process. This calls
Py_FinalizeExand then calls the standard C library functionexit(status). IfPy_FinalizeExindicates an error, the exit status is set to 120.3.6 Errors from finalization no longer ignored.
single: Py_FinalizeEx (C function) single: cleanup functions
Register a cleanup function to be called by
Py_FinalizeEx. The cleanup function will be called with no arguments and should return no value. At most 32 cleanup functions can be registered. When the registration is successful,Py_AtExitreturns0; on failure, it returns-1. The cleanup function registered last is called first. Each cleanup function will be called at most once. Since Python's internal finalization will have completed before the cleanup function, no Python APIs should be called by func.
PyUnstable_AtExitfor passing avoid *dataargument.
谢谢你的反馈!