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 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
238 .. _systemfunctions:
239
240 System Functions
241 ================
242
243 These are utility functions that make functionality from the :mod:`sys` module
244 accessible to C code. They all work with the current interpreter thread's
245 :mod:`sys` module's dict, which is contained in the internal thread state structure.
246
247 .. c:function:: PyObject *PySys_GetObject(const char *name)
248
249 Return the object *name* from the :mod:`sys` module or ``NULL`` if it does
250 not exist, without setting an exception.
251
252 .. c:function:: int PySys_SetObject(const char *name, PyObject *v)
253
254 Set *name* in the :mod:`sys` module to *v* unless *v* is ``NULL``, in which
255 case *name* is deleted from the sys module. Returns ``0`` on success, ``-1``
256 on error.
257
258 .. c:function:: void PySys_ResetWarnOptions()
259
260 Reset :data:`sys.warnoptions` to an empty list. This function may be
261 called prior to :c:func:`Py_Initialize`.
262
263 .. deprecated-removed:: 3.13 3.15
264 Clear :data:`sys.warnoptions` and :data:`!warnings.filters` instead.
265
266 .. c:function:: void PySys_WriteStdout(const char *format, ...)
267
268 Write the output string described by *format* to :data:`sys.stdout`. No
269 exceptions are raised, even if truncation occurs (see below).
270
271 *format* should limit the total size of the formatted output string to
272 1000 bytes or less -- after 1000 bytes, the output string is truncated.
273 In particular, this means that no unrestricted "%s" formats should occur;
274 these should be limited using "%.<N>s" where <N> is a decimal number
275 calculated so that <N> plus the maximum size of other formatted text does not
276 exceed 1000 bytes. Also watch out for "%f", which can print hundreds of
277 digits for very large numbers.
278
279 If a problem occurs, or :data:`sys.stdout` is unset, the formatted message
280 is written to the real (C level) *stdout*.
281
282 .. c:function:: void PySys_WriteStderr(const char *format, ...)
283
284 As :c:func:`PySys_WriteStdout`, but write to :data:`sys.stderr` or *stderr*
285 instead.
286
287 .. c:function:: void PySys_FormatStdout(const char *format, ...)
288
289 Function similar to PySys_WriteStdout() but format the message using
290 :c:func:`PyUnicode_FromFormatV` and don't truncate the message to an
291 arbitrary length.
292
293 .. versionadded:: 3.2
294
295 .. c:function:: void PySys_FormatStderr(const char *format, ...)
296
297 As :c:func:`PySys_FormatStdout`, but write to :data:`sys.stderr` or *stderr*
298 instead.
299
300 .. versionadded:: 3.2
301
302 .. c:function:: PyObject *PySys_GetXOptions()
303
304 Return the current dictionary of :option:`-X` options, similarly to
305 :data:`sys._xoptions`. On error, ``NULL`` is returned and an exception is
306 set.
307
308 .. versionadded:: 3.2
309
310
311 .. c:function:: int PySys_Audit(const char *event, const char *format, ...)
312
313 Raise an auditing event with any active hooks. Return zero for success
314 and non-zero with an exception set on failure.
315
316 The *event* string argument must not be *NULL*.
317
318 If any hooks have been added, *format* and other arguments will be used
319 to construct a tuple to pass. Apart from ``N``, the same format characters
320 as used in :c:func:`Py_BuildValue` are available. If the built value is not
321 a tuple, it will be added into a single-element tuple.
322
323 The ``N`` format option must not be used. It consumes a reference, but since
324 there is no way to know whether arguments to this function will be consumed,
325 using it may cause reference leaks.
326
327 Note that ``#`` format characters should always be treated as
328 :c:type:`Py_ssize_t`, regardless of whether ``PY_SSIZE_T_CLEAN`` was defined.
329
330 :func:`sys.audit` performs the same function from Python code.
331
332 See also :c:func:`PySys_AuditTuple`.
333
334 .. versionadded:: 3.8
335
336 .. versionchanged:: 3.8.2
337
338 Require :c:type:`Py_ssize_t` for ``#`` format characters. Previously, an
339 unavoidable deprecation warning was raised.
340
341
342 .. c:function:: int PySys_AuditTuple(const char *event, PyObject *args)
343
344 Similar to :c:func:`PySys_Audit`, but pass arguments as a Python object.
345 *args* must be a :class:`tuple`. To pass no arguments, *args* can be *NULL*.
346
347 .. versionadded:: 3.13
348
349
350 .. c:function:: int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
351
352 Append the callable *hook* to the list of active auditing hooks.
353 Return zero on success
354 and non-zero on failure. If the runtime has been initialized, also set an
355 error on failure. Hooks added through this API are called for all
356 interpreters created by the runtime.
357
358 The *userData* pointer is passed into the hook function. Since hook
359 functions may be called from different runtimes, this pointer should not
360 refer directly to Python state.
361
362 This function is safe to call before :c:func:`Py_Initialize`. When called
363 after runtime initialization, existing audit hooks are notified and may
364 silently abort the operation by raising an error subclassed from
365 :class:`Exception` (other errors will not be silenced).
366
367 The hook function is always called with the GIL held by the Python
368 interpreter that raised the event.
369
370 See :pep:`578` for a detailed description of auditing. Functions in the
371 runtime and standard library that raise events are listed in the
372 :ref:`audit events table <audit-events>`.
373 Details are in each function's documentation.
374
375 .. audit-event:: sys.addaudithook "" c.PySys_AddAuditHook
376
377 If the interpreter is initialized, this function raises an auditing event
378 ``sys.addaudithook`` with no arguments. If any existing hooks raise an
379 exception derived from :class:`Exception`, the new hook will not be
380 added and the exception is cleared. As a result, callers cannot assume
381 that their hook has been added unless they control all existing hooks.
382
383 .. c:namespace:: NULL
384 .. c:type:: int (*Py_AuditHookFunction) (const char *event, PyObject *args, void *userData)
385
386 The type of the hook function.
387 *event* is the C string event argument passed to :c:func:`PySys_Audit` or
388 :c:func:`PySys_AuditTuple`.
389 *args* is guaranteed to be a :c:type:`PyTupleObject`.
390 *userData* is the argument passed to PySys_AddAuditHook().
391
392 .. versionadded:: 3.8
393
394
395 .. _processcontrol:
396
397 Process Control
398 ===============
399
400
401 .. c:function:: void Py_FatalError(const char *message)
402
403 .. index:: single: abort (C function)
404
405 Print a fatal error message and kill the process. No cleanup is performed.
406 This function should only be invoked when a condition is detected that would
407 make it dangerous to continue using the Python interpreter; e.g., when the
408 object administration appears to be corrupted. On Unix, the standard C library
409 function :c:func:`!abort` is called which will attempt to produce a :file:`core`
410 file.
411
412 The ``Py_FatalError()`` function is replaced with a macro which logs
413 automatically the name of the current function, unless the
414 ``Py_LIMITED_API`` macro is defined.
415
416 .. versionchanged:: 3.9
417 Log the function name automatically.
418
419
420 .. c:function:: void Py_Exit(int status)
421
422 .. index::
423 single: Py_FinalizeEx (C function)
424 single: exit (C function)
425
426 Exit the current process. This calls :c:func:`Py_FinalizeEx` and then calls the
427 standard C library function ``exit(status)``. If :c:func:`Py_FinalizeEx`
428 indicates an error, the exit status is set to 120.
429
430 .. versionchanged:: 3.6
431 Errors from finalization no longer ignored.
432
433
434 .. c:function:: int Py_AtExit(void (*func) ())
435
436 .. index::
437 single: Py_FinalizeEx (C function)
438 single: cleanup functions
439
440 Register a cleanup function to be called by :c:func:`Py_FinalizeEx`. The cleanup
441 function will be called with no arguments and should return no value. At most
442 32 cleanup functions can be registered. When the registration is successful,
443 :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup
444 function registered last is called first. Each cleanup function will be called
445 at most once. Since Python's internal finalization will have completed before
446 the cleanup function, no Python APIs should be called by *func*.
447
448 .. seealso::
449
450 :c:func:`PyUnstable_AtExit` for passing a ``void *data`` argument.