• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. highlight:: c
2
3.. _os:
4
5Operating 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.. c:function:: wchar_t* Py_DecodeLocale(const char* arg, size_t *size)
127
128   .. warning::
129      This function should not be called directly: use the :c:type:`PyConfig`
130      API with the :c:func:`PyConfig_SetBytesString` function which ensures
131      that :ref:`Python is preinitialized <c-preinit>`.
132
133      This function must not be called before :ref:`Python is preinitialized
134      <c-preinit>` and so that the LC_CTYPE locale is properly configured: see
135      the :c:func:`Py_PreInitialize` function.
136
137   Decode a byte string from the :term:`filesystem encoding and error handler`.
138   If the error handler is :ref:`surrogateescape error handler
139   <surrogateescape>`, undecodable bytes are decoded as characters in range
140   U+DC80..U+DCFF; and if a byte sequence can be decoded as a surrogate
141   character, the bytes are escaped using the surrogateescape error handler
142   instead of decoding them.
143
144   Return a pointer to a newly allocated wide character string, use
145   :c:func:`PyMem_RawFree` to free the memory. If size is not ``NULL``, write
146   the number of wide characters excluding the null character into ``*size``
147
148   Return ``NULL`` on decoding error or memory allocation error. If *size* is
149   not ``NULL``, ``*size`` is set to ``(size_t)-1`` on memory error or set to
150   ``(size_t)-2`` on decoding error.
151
152   The :term:`filesystem encoding and error handler` are selected by
153   :c:func:`PyConfig_Read`: see :c:member:`~PyConfig.filesystem_encoding` and
154   :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
155
156   Decoding errors should never happen, unless there is a bug in the C
157   library.
158
159   Use the :c:func:`Py_EncodeLocale` function to encode the character string
160   back to a byte string.
161
162   .. seealso::
163
164      The :c:func:`PyUnicode_DecodeFSDefaultAndSize` and
165      :c:func:`PyUnicode_DecodeLocaleAndSize` functions.
166
167   .. versionadded:: 3.5
168
169   .. versionchanged:: 3.7
170      The function now uses the UTF-8 encoding in the :ref:`Python UTF-8 Mode
171      <utf8-mode>`.
172
173   .. versionchanged:: 3.8
174      The function now uses the UTF-8 encoding on Windows if
175      :c:member:`PyPreConfig.legacy_windows_fs_encoding` is zero;
176
177
178.. c:function:: char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
179
180   Encode a wide character string to the :term:`filesystem encoding and error
181   handler`. If the error handler is :ref:`surrogateescape error handler
182   <surrogateescape>`, surrogate characters in the range U+DC80..U+DCFF are
183   converted to bytes 0x80..0xFF.
184
185   Return a pointer to a newly allocated byte string, use :c:func:`PyMem_Free`
186   to free the memory. Return ``NULL`` on encoding error or memory allocation
187   error.
188
189   If error_pos is not ``NULL``, ``*error_pos`` is set to ``(size_t)-1`` on
190   success,  or set to the index of the invalid character on encoding error.
191
192   The :term:`filesystem encoding and error handler` are selected by
193   :c:func:`PyConfig_Read`: see :c:member:`~PyConfig.filesystem_encoding` and
194   :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
195
196   Use the :c:func:`Py_DecodeLocale` function to decode the bytes string back
197   to a wide character string.
198
199   .. warning::
200      This function must not be called before :ref:`Python is preinitialized
201      <c-preinit>` and so that the LC_CTYPE locale is properly configured: see
202      the :c:func:`Py_PreInitialize` function.
203
204   .. seealso::
205
206      The :c:func:`PyUnicode_EncodeFSDefault` and
207      :c:func:`PyUnicode_EncodeLocale` functions.
208
209   .. versionadded:: 3.5
210
211   .. versionchanged:: 3.7
212      The function now uses the UTF-8 encoding in the :ref:`Python UTF-8 Mode
213      <utf8-mode>`.
214
215   .. versionchanged:: 3.8
216      The function now uses the UTF-8 encoding on Windows if
217      :c:member:`PyPreConfig.legacy_windows_fs_encoding` is zero.
218
219
220.. _systemfunctions:
221
222System Functions
223================
224
225These are utility functions that make functionality from the :mod:`sys` module
226accessible to C code.  They all work with the current interpreter thread's
227:mod:`sys` module's dict, which is contained in the internal thread state structure.
228
229.. c:function:: PyObject *PySys_GetObject(const char *name)
230
231   Return the object *name* from the :mod:`sys` module or ``NULL`` if it does
232   not exist, without setting an exception.
233
234.. c:function:: int PySys_SetObject(const char *name, PyObject *v)
235
236   Set *name* in the :mod:`sys` module to *v* unless *v* is ``NULL``, in which
237   case *name* is deleted from the sys module. Returns ``0`` on success, ``-1``
238   on error.
239
240.. c:function:: void PySys_ResetWarnOptions()
241
242   Reset :data:`sys.warnoptions` to an empty list. This function may be
243   called prior to :c:func:`Py_Initialize`.
244
245   .. deprecated-removed:: 3.13 3.15
246      Clear :data:`sys.warnoptions` and :data:`!warnings.filters` instead.
247
248.. c:function:: void PySys_WriteStdout(const char *format, ...)
249
250   Write the output string described by *format* to :data:`sys.stdout`.  No
251   exceptions are raised, even if truncation occurs (see below).
252
253   *format* should limit the total size of the formatted output string to
254   1000 bytes or less -- after 1000 bytes, the output string is truncated.
255   In particular, this means that no unrestricted "%s" formats should occur;
256   these should be limited using "%.<N>s" where <N> is a decimal number
257   calculated so that <N> plus the maximum size of other formatted text does not
258   exceed 1000 bytes.  Also watch out for "%f", which can print hundreds of
259   digits for very large numbers.
260
261   If a problem occurs, or :data:`sys.stdout` is unset, the formatted message
262   is written to the real (C level) *stdout*.
263
264.. c:function:: void PySys_WriteStderr(const char *format, ...)
265
266   As :c:func:`PySys_WriteStdout`, but write to :data:`sys.stderr` or *stderr*
267   instead.
268
269.. c:function:: void PySys_FormatStdout(const char *format, ...)
270
271   Function similar to PySys_WriteStdout() but format the message using
272   :c:func:`PyUnicode_FromFormatV` and don't truncate the message to an
273   arbitrary length.
274
275   .. versionadded:: 3.2
276
277.. c:function:: void PySys_FormatStderr(const char *format, ...)
278
279   As :c:func:`PySys_FormatStdout`, but write to :data:`sys.stderr` or *stderr*
280   instead.
281
282   .. versionadded:: 3.2
283
284.. c:function:: PyObject *PySys_GetXOptions()
285
286   Return the current dictionary of :option:`-X` options, similarly to
287   :data:`sys._xoptions`.  On error, ``NULL`` is returned and an exception is
288   set.
289
290   .. versionadded:: 3.2
291
292
293.. c:function:: int PySys_Audit(const char *event, const char *format, ...)
294
295   Raise an auditing event with any active hooks. Return zero for success
296   and non-zero with an exception set on failure.
297
298   The *event* string argument must not be *NULL*.
299
300   If any hooks have been added, *format* and other arguments will be used
301   to construct a tuple to pass. Apart from ``N``, the same format characters
302   as used in :c:func:`Py_BuildValue` are available. If the built value is not
303   a tuple, it will be added into a single-element tuple.
304
305   The ``N`` format option must not be used. It consumes a reference, but since
306   there is no way to know whether arguments to this function will be consumed,
307   using it may cause reference leaks.
308
309   Note that ``#`` format characters should always be treated as
310   :c:type:`Py_ssize_t`, regardless of whether ``PY_SSIZE_T_CLEAN`` was defined.
311
312   :func:`sys.audit` performs the same function from Python code.
313
314   See also :c:func:`PySys_AuditTuple`.
315
316   .. versionadded:: 3.8
317
318   .. versionchanged:: 3.8.2
319
320      Require :c:type:`Py_ssize_t` for ``#`` format characters. Previously, an
321      unavoidable deprecation warning was raised.
322
323
324.. c:function:: int PySys_AuditTuple(const char *event, PyObject *args)
325
326   Similar to :c:func:`PySys_Audit`, but pass arguments as a Python object.
327   *args* must be a :class:`tuple`. To pass no arguments, *args* can be *NULL*.
328
329   .. versionadded:: 3.13
330
331
332.. c:function:: int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
333
334   Append the callable *hook* to the list of active auditing hooks.
335   Return zero on success
336   and non-zero on failure. If the runtime has been initialized, also set an
337   error on failure. Hooks added through this API are called for all
338   interpreters created by the runtime.
339
340   The *userData* pointer is passed into the hook function. Since hook
341   functions may be called from different runtimes, this pointer should not
342   refer directly to Python state.
343
344   This function is safe to call before :c:func:`Py_Initialize`. When called
345   after runtime initialization, existing audit hooks are notified and may
346   silently abort the operation by raising an error subclassed from
347   :class:`Exception` (other errors will not be silenced).
348
349   The hook function is always called with the GIL held by the Python
350   interpreter that raised the event.
351
352   See :pep:`578` for a detailed description of auditing.  Functions in the
353   runtime and standard library that raise events are listed in the
354   :ref:`audit events table <audit-events>`.
355   Details are in each function's documentation.
356
357   .. audit-event:: sys.addaudithook "" c.PySys_AddAuditHook
358
359      If the interpreter is initialized, this function raises an auditing event
360      ``sys.addaudithook`` with no arguments. If any existing hooks raise an
361      exception derived from :class:`Exception`, the new hook will not be
362      added and the exception is cleared. As a result, callers cannot assume
363      that their hook has been added unless they control all existing hooks.
364
365   .. c:namespace:: NULL
366   .. c:type:: int (*Py_AuditHookFunction) (const char *event, PyObject *args, void *userData)
367
368      The type of the hook function.
369      *event* is the C string event argument passed to :c:func:`PySys_Audit` or
370      :c:func:`PySys_AuditTuple`.
371      *args* is guaranteed to be a :c:type:`PyTupleObject`.
372      *userData* is the argument passed to PySys_AddAuditHook().
373
374   .. versionadded:: 3.8
375
376
377.. _processcontrol:
378
379Process Control
380===============
381
382
383.. c:function:: void Py_FatalError(const char *message)
384
385   .. index:: single: abort (C function)
386
387   Print a fatal error message and kill the process.  No cleanup is performed.
388   This function should only be invoked when a condition is detected that would
389   make it dangerous to continue using the Python interpreter; e.g., when the
390   object administration appears to be corrupted.  On Unix, the standard C library
391   function :c:func:`!abort` is called which will attempt to produce a :file:`core`
392   file.
393
394   The ``Py_FatalError()`` function is replaced with a macro which logs
395   automatically the name of the current function, unless the
396   ``Py_LIMITED_API`` macro is defined.
397
398   .. versionchanged:: 3.9
399      Log the function name automatically.
400
401
402.. c:function:: void Py_Exit(int status)
403
404   .. index::
405      single: Py_FinalizeEx (C function)
406      single: exit (C function)
407
408   Exit the current process.  This calls :c:func:`Py_FinalizeEx` and then calls the
409   standard C library function ``exit(status)``.  If :c:func:`Py_FinalizeEx`
410   indicates an error, the exit status is set to 120.
411
412   .. versionchanged:: 3.6
413      Errors from finalization no longer ignored.
414
415
416.. c:function:: int Py_AtExit(void (*func) ())
417
418   .. index::
419      single: Py_FinalizeEx (C function)
420      single: cleanup functions
421
422   Register a cleanup function to be called by :c:func:`Py_FinalizeEx`.  The cleanup
423   function will be called with no arguments and should return no value.  At most
424   32 cleanup functions can be registered.  When the registration is successful,
425   :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``.  The cleanup
426   function registered last is called first. Each cleanup function will be called
427   at most once.  Since Python's internal finalization will have completed before
428   the cleanup function, no Python APIs should be called by *func*.
429