Debian Codegraph @

Doc/c-api/sys.rst

raw
1 .. highlight:: c
2
3 .. _os:
4
5 Operating System Utilities
6 ==========================
7
8
9 .. c:function:: PyObject* PyOS_FSPath(PyObject *path)
10
11 Return the file system representation for *path*. If the object is a
12 :class:`str` or :class:`bytes` object, then a new
13 :term:`strong reference` is returned.
14 If the object implements the :class:`os.PathLike` interface,
15 then :meth:`~os.PathLike.__fspath__` is returned as long as it is a
16 :class:`str` or :class:`bytes` object. Otherwise :exc:`TypeError` is raised
17 and ``NULL`` is returned.
18
19 .. versionadded:: 3.6
20
21
22 .. c:function:: int Py_FdIsInteractive(FILE *fp, const char *filename)
23
24 Return true (nonzero) if the standard I/O file *fp* with name *filename* is
25 deemed interactive. This is the case for files for which ``isatty(fileno(fp))``
26 is true. If the :c:member:`PyConfig.interactive` is non-zero, this function
27 also returns true if the *filename* pointer is ``NULL`` or if the name is equal to
28 one of the strings ``'<stdin>'`` or ``'???'``.
29
30 This function must not be called before Python is initialized.
31
32
33 .. c:function:: void PyOS_BeforeFork()
34
35 Function to prepare some internal state before a process fork. This
36 should be called before calling :c:func:`fork` or any similar function
37 that clones the current process.
38 Only available on systems where :c:func:`fork` is defined.
39
40 .. warning::
41 The C :c:func:`fork` call should only be made from the
42 :ref:`"main" thread <fork-and-threads>` (of the
43 :ref:`"main" interpreter <sub-interpreter-support>`). The same is
44 true for ``PyOS_BeforeFork()``.
45
46 .. versionadded:: 3.7
47
48
49 .. c:function:: void PyOS_AfterFork_Parent()
50
51 Function to update some internal state after a process fork. This
52 should be called from the parent process after calling :c:func:`fork`
53 or any similar function that clones the current process, regardless
54 of whether process cloning was successful.
55 Only available on systems where :c:func:`fork` is defined.
56
57 .. warning::
58 The C :c:func:`fork` call should only be made from the
59 :ref:`"main" thread <fork-and-threads>` (of the
60 :ref:`"main" interpreter <sub-interpreter-support>`). The same is
61 true for ``PyOS_AfterFork_Parent()``.
62
63 .. versionadded:: 3.7
64
65
66 .. c:function:: void PyOS_AfterFork_Child()
67
68 Function to update internal interpreter state after a process fork.
69 This must be called from the child process after calling :c:func:`fork`,
70 or any similar function that clones the current process, if there is
71 any chance the process will call back into the Python interpreter.
72 Only available on systems where :c:func:`fork` is defined.
73
74 .. warning::
75 The C :c:func:`fork` call should only be made from the
76 :ref:`"main" thread <fork-and-threads>` (of the
77 :ref:`"main" interpreter <sub-interpreter-support>`). The same is
78 true for ``PyOS_AfterFork_Child()``.
79
80 .. versionadded:: 3.7
81
82 .. seealso::
83 :func:`os.register_at_fork` allows registering custom Python functions
84 to be called by :c:func:`PyOS_BeforeFork()`,
85 :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`.
86
87
88 .. c:function:: void PyOS_AfterFork()
89
90 Function to update some internal state after a process fork; this should be
91 called in the new process if the Python interpreter will continue to be used.
92 If a new executable is loaded into the new process, this function does not need
93 to be called.
94
95 .. deprecated:: 3.7
96 This function is superseded by :c:func:`PyOS_AfterFork_Child()`.
97
98
99 .. c:function:: int PyOS_CheckStack()
100
101 .. index:: single: USE_STACKCHECK (C macro)
102
103 Return true when the interpreter runs out of stack space. This is a reliable
104 check, but is only available when :c:macro:`!USE_STACKCHECK` is defined (currently
105 on certain versions of Windows using the Microsoft Visual C++ compiler).
106 :c:macro:`!USE_STACKCHECK` will be defined automatically; you should never
107 change the definition in your own code.
108
109
110 .. c:type:: void (*PyOS_sighandler_t)(int)
111
112
113 .. c:function:: PyOS_sighandler_t PyOS_getsig(int i)
114
115 Return the current signal handler for signal *i*. This is a thin wrapper around
116 either :c:func:`!sigaction` or :c:func:`!signal`. Do not call those functions
117 directly!
118
119
120 .. c:function:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)
121
122 Set the signal handler for signal *i* to be *h*; return the old signal handler.
123 This is a thin wrapper around either :c:func:`!sigaction` or :c:func:`!signal`. Do
124 not call those functions directly!
125
126
127 .. c:function:: int PyOS_InterruptOccurred(void)
128
129 Check if a :c:macro:`!SIGINT` signal has been received.
130
131 Returns ``1`` if a :c:macro:`!SIGINT` has occurred and clears the signal flag,
132 or ``0`` otherwise.
133
134 In most cases, you should prefer :c:func:`PyErr_CheckSignals` over this function.
135 :c:func:`!PyErr_CheckSignals` invokes the appropriate signal handlers
136 for all pending signals, allowing Python code to handle the signal properly.
137 This function only detects :c:macro:`!SIGINT` and does not invoke any Python
138 signal handlers.
139
140 This function is async-signal-safe and this function cannot fail.
141 The caller must hold an :term:`attached thread state`.
142
143
144 .. c:function:: wchar_t* Py_DecodeLocale(const char* arg, size_t *size)
145
146 .. warning::
147 This function should not be called directly: use the :c:type:`PyConfig`
148 API with the :c:func:`PyConfig_SetBytesString` function which ensures
149 that :ref:`Python is preinitialized <c-preinit>`.
150
151 This function must not be called before :ref:`Python is preinitialized
152 <c-preinit>` and so that the LC_CTYPE locale is properly configured: see
153 the :c:func:`Py_PreInitialize` function.
154
155 Decode a byte string from the :term:`filesystem encoding and error handler`.
156 If the error handler is :ref:`surrogateescape error handler
157 <surrogateescape>`, undecodable bytes are decoded as characters in range
158 U+DC80..U+DCFF; and if a byte sequence can be decoded as a surrogate
159 character, the bytes are escaped using the surrogateescape error handler
160 instead of decoding them.
161
162 Return a pointer to a newly allocated wide character string, use
163 :c:func:`PyMem_RawFree` to free the memory. If size is not ``NULL``, write
164 the number of wide characters excluding the null character into ``*size``
165
166 Return ``NULL`` on decoding error or memory allocation error. If *size* is
167 not ``NULL``, ``*size`` is set to ``(size_t)-1`` on memory error or set to
168 ``(size_t)-2`` on decoding error.
169
170 The :term:`filesystem encoding and error handler` are selected by
171 :c:func:`PyConfig_Read`: see :c:member:`~PyConfig.filesystem_encoding` and
172 :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
173
174 Decoding errors should never happen, unless there is a bug in the C
175 library.
176
177 Use the :c:func:`Py_EncodeLocale` function to encode the character string
178 back to a byte string.
179
180 .. seealso::
181
182 The :c:func:`PyUnicode_DecodeFSDefaultAndSize` and
183 :c:func:`PyUnicode_DecodeLocaleAndSize` functions.
184
185 .. versionadded:: 3.5
186
187 .. versionchanged:: 3.7
188 The function now uses the UTF-8 encoding in the :ref:`Python UTF-8 Mode
189 <utf8-mode>`.
190
191 .. versionchanged:: 3.8
192 The function now uses the UTF-8 encoding on Windows if
193 :c:member:`PyPreConfig.legacy_windows_fs_encoding` is zero;
194
195
196 .. c:function:: char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
197
198 Encode a wide character string to the :term:`filesystem encoding and error
199 handler`. If the error handler is :ref:`surrogateescape error handler
200 <surrogateescape>`, surrogate characters in the range U+DC80..U+DCFF are
201 converted to bytes 0x80..0xFF.
202
203 Return a pointer to a newly allocated byte string, use :c:func:`PyMem_Free`
204 to free the memory. Return ``NULL`` on encoding error or memory allocation
205 error.
206
207 If error_pos is not ``NULL``, ``*error_pos`` is set to ``(size_t)-1`` on
208 success, or set to the index of the invalid character on encoding error.
209
210 The :term:`filesystem encoding and error handler` are selected by
211 :c:func:`PyConfig_Read`: see :c:member:`~PyConfig.filesystem_encoding` and
212 :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
213
214 Use the :c:func:`Py_DecodeLocale` function to decode the bytes string back
215 to a wide character string.
216
217 .. warning::
218 This function must not be called before :ref:`Python is preinitialized
219 <c-preinit>` and so that the LC_CTYPE locale is properly configured: see
220 the :c:func:`Py_PreInitialize` function.
221
222 .. seealso::
223
224 The :c:func:`PyUnicode_EncodeFSDefault` and
225 :c:func:`PyUnicode_EncodeLocale` functions.
226
227 .. versionadded:: 3.5
228
229 .. versionchanged:: 3.7
230 The function now uses the UTF-8 encoding in the :ref:`Python UTF-8 Mode
231 <utf8-mode>`.
232
233 .. versionchanged:: 3.8
234 The function now uses the UTF-8 encoding on Windows if
235 :c:member:`PyPreConfig.legacy_windows_fs_encoding` is zero.
236
237 .. c:function:: FILE* Py_fopen(PyObject *path, const char *mode)
238
239 Similar to :c:func:`!fopen`, but *path* is a Python object and
240 an exception is set on error.
241
242 *path* must be a :class:`str` object, a :class:`bytes` object,
243 or a :term:`path-like object`.
244
245 On success, return the new file pointer.
246 On error, set an exception and return ``NULL``.
247
248 The file must be closed by :c:func:`Py_fclose` rather than calling directly
249 :c:func:`!fclose`.
250
251 The file descriptor is created non-inheritable (:pep:`446`).
252
253 The caller must have an :term:`attached thread state`.
254
255 .. versionadded:: 3.14
256
257
258 .. c:function:: int Py_fclose(FILE *file)
259
260 Close a file that was opened by :c:func:`Py_fopen`.
261
262 On success, return ``0``.
263 On error, return ``EOF`` and ``errno`` is set to indicate the error.
264 In either case, any further access (including another call to
265 :c:func:`Py_fclose`) to the stream results in undefined behavior.
266
267 .. versionadded:: 3.14
268
269
270 .. _systemfunctions:
271
272 System Functions
273 ================
274
275 These are utility functions that make functionality from the :mod:`sys` module
276 accessible to C code. They all work with the current interpreter thread's
277 :mod:`sys` module's dict, which is contained in the internal thread state structure.
278
279 .. c:function:: PyObject *PySys_GetObject(const char *name)
280
281 Return the object *name* from the :mod:`sys` module or ``NULL`` if it does
282 not exist, without setting an exception.
283
284 .. c:function:: int PySys_SetObject(const char *name, PyObject *v)
285
286 Set *name* in the :mod:`sys` module to *v* unless *v* is ``NULL``, in which
287 case *name* is deleted from the sys module. Returns ``0`` on success, ``-1``
288 on error.
289
290 .. c:function:: void PySys_ResetWarnOptions()
291
292 Reset :data:`sys.warnoptions` to an empty list. This function may be
293 called prior to :c:func:`Py_Initialize`.
294
295 .. deprecated-removed:: 3.13 3.15
296 Clear :data:`sys.warnoptions` and :data:`!warnings.filters` instead.
297
298 .. c:function:: void PySys_WriteStdout(const char *format, ...)
299
300 Write the output string described by *format* to :data:`sys.stdout`. No
301 exceptions are raised, even if truncation occurs (see below).
302
303 *format* should limit the total size of the formatted output string to
304 1000 bytes or less -- after 1000 bytes, the output string is truncated.
305 In particular, this means that no unrestricted "%s" formats should occur;
306 these should be limited using "%.<N>s" where <N> is a decimal number
307 calculated so that <N> plus the maximum size of other formatted text does not
308 exceed 1000 bytes. Also watch out for "%f", which can print hundreds of
309 digits for very large numbers.
310
311 If a problem occurs, or :data:`sys.stdout` is unset, the formatted message
312 is written to the real (C level) *stdout*.
313
314 .. c:function:: void PySys_WriteStderr(const char *format, ...)
315
316 As :c:func:`PySys_WriteStdout`, but write to :data:`sys.stderr` or *stderr*
317 instead.
318
319 .. c:function:: void PySys_FormatStdout(const char *format, ...)
320
321 Function similar to PySys_WriteStdout() but format the message using
322 :c:func:`PyUnicode_FromFormatV` and don't truncate the message to an
323 arbitrary length.
324
325 .. versionadded:: 3.2
326
327 .. c:function:: void PySys_FormatStderr(const char *format, ...)
328
329 As :c:func:`PySys_FormatStdout`, but write to :data:`sys.stderr` or *stderr*
330 instead.
331
332 .. versionadded:: 3.2
333
334 .. c:function:: PyObject *PySys_GetXOptions()
335
336 Return the current dictionary of :option:`-X` options, similarly to
337 :data:`sys._xoptions`. On error, ``NULL`` is returned and an exception is
338 set.
339
340 .. versionadded:: 3.2
341
342
343 .. c:function:: int PySys_Audit(const char *event, const char *format, ...)
344
345 Raise an auditing event with any active hooks. Return zero for success
346 and non-zero with an exception set on failure.
347
348 The *event* string argument must not be *NULL*.
349
350 If any hooks have been added, *format* and other arguments will be used
351 to construct a tuple to pass. Apart from ``N``, the same format characters
352 as used in :c:func:`Py_BuildValue` are available. If the built value is not
353 a tuple, it will be added into a single-element tuple.
354
355 The ``N`` format option must not be used. It consumes a reference, but since
356 there is no way to know whether arguments to this function will be consumed,
357 using it may cause reference leaks.
358
359 Note that ``#`` format characters should always be treated as
360 :c:type:`Py_ssize_t`, regardless of whether ``PY_SSIZE_T_CLEAN`` was defined.
361
362 :func:`sys.audit` performs the same function from Python code.
363
364 See also :c:func:`PySys_AuditTuple`.
365
366 .. versionadded:: 3.8
367
368 .. versionchanged:: 3.8.2
369
370 Require :c:type:`Py_ssize_t` for ``#`` format characters. Previously, an
371 unavoidable deprecation warning was raised.
372
373
374 .. c:function:: int PySys_AuditTuple(const char *event, PyObject *args)
375
376 Similar to :c:func:`PySys_Audit`, but pass arguments as a Python object.
377 *args* must be a :class:`tuple`. To pass no arguments, *args* can be *NULL*.
378
379 .. versionadded:: 3.13
380
381
382 .. c:function:: int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
383
384 Append the callable *hook* to the list of active auditing hooks.
385 Return zero on success
386 and non-zero on failure. If the runtime has been initialized, also set an
387 error on failure. Hooks added through this API are called for all
388 interpreters created by the runtime.
389
390 The *userData* pointer is passed into the hook function. Since hook
391 functions may be called from different runtimes, this pointer should not
392 refer directly to Python state.
393
394 This function is safe to call before :c:func:`Py_Initialize`. When called
395 after runtime initialization, existing audit hooks are notified and may
396 silently abort the operation by raising an error subclassed from
397 :class:`Exception` (other errors will not be silenced).
398
399 The hook function is always called with an :term:`attached thread state` by
400 the Python interpreter that raised the event.
401
402 See :pep:`578` for a detailed description of auditing. Functions in the
403 runtime and standard library that raise events are listed in the
404 :ref:`audit events table <audit-events>`.
405 Details are in each function's documentation.
406
407 .. audit-event:: sys.addaudithook "" c.PySys_AddAuditHook
408
409 If the interpreter is initialized, this function raises an auditing event
410 ``sys.addaudithook`` with no arguments. If any existing hooks raise an
411 exception derived from :class:`Exception`, the new hook will not be
412 added and the exception is cleared. As a result, callers cannot assume
413 that their hook has been added unless they control all existing hooks.
414
415 .. c:namespace:: NULL
416 .. c:type:: int (*Py_AuditHookFunction) (const char *event, PyObject *args, void *userData)
417
418 The type of the hook function.
419 *event* is the C string event argument passed to :c:func:`PySys_Audit` or
420 :c:func:`PySys_AuditTuple`.
421 *args* is guaranteed to be a :c:type:`PyTupleObject`.
422 *userData* is the argument passed to PySys_AddAuditHook().
423
424 .. versionadded:: 3.8
425
426
427 .. _processcontrol:
428
429 Process Control
430 ===============
431
432
433 .. c:function:: void Py_FatalError(const char *message)
434
435 .. index:: single: abort (C function)
436
437 Print a fatal error message and kill the process. No cleanup is performed.
438 This function should only be invoked when a condition is detected that would
439 make it dangerous to continue using the Python interpreter; e.g., when the
440 object administration appears to be corrupted. On Unix, the standard C library
441 function :c:func:`!abort` is called which will attempt to produce a :file:`core`
442 file.
443
444 The ``Py_FatalError()`` function is replaced with a macro which logs
445 automatically the name of the current function, unless the
446 ``Py_LIMITED_API`` macro is defined.
447
448 .. versionchanged:: 3.9
449 Log the function name automatically.
450
451
452 .. c:function:: void Py_Exit(int status)
453
454 .. index::
455 single: Py_FinalizeEx (C function)
456 single: exit (C function)
457
458 Exit the current process. This calls :c:func:`Py_FinalizeEx` and then calls the
459 standard C library function ``exit(status)``. If :c:func:`Py_FinalizeEx`
460 indicates an error, the exit status is set to 120.
461
462 .. versionchanged:: 3.6
463 Errors from finalization no longer ignored.
464
465
466 .. c:function:: int Py_AtExit(void (*func) ())
467
468 .. index::
469 single: Py_FinalizeEx (C function)
470 single: cleanup functions
471
472 Register a cleanup function to be called by :c:func:`Py_FinalizeEx`. The cleanup
473 function will be called with no arguments and should return no value. At most
474 32 cleanup functions can be registered. When the registration is successful,
475 :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup
476 function registered last is called first. Each cleanup function will be called
477 at most once. Since Python's internal finalization will have completed before
478 the cleanup function, no Python APIs should be called by *func*.
479
480 .. seealso::
481
482 :c:func:`PyUnstable_AtExit` for passing a ``void *data`` argument.