| 1 |
:mod:`!sys` --- System-specific parameters and functions |
| 2 |
======================================================== |
| 3 |
|
| 4 |
.. module:: sys |
| 5 |
:synopsis: Access system-specific parameters and functions. |
| 6 |
|
| 7 |
-------------- |
| 8 |
|
| 9 |
This module provides access to some variables used or maintained by the |
| 10 |
interpreter and to functions that interact strongly with the interpreter. It is |
| 11 |
always available. Unless explicitly noted otherwise, all variables are read-only. |
| 12 |
|
| 13 |
|
| 14 |
.. data:: abiflags |
| 15 |
|
| 16 |
On POSIX systems where Python was built with the standard ``configure`` |
| 17 |
script, this contains the ABI flags as specified by :pep:`3149`. |
| 18 |
|
| 19 |
.. versionadded:: 3.2 |
| 20 |
|
| 21 |
.. versionchanged:: 3.8 |
| 22 |
Default flags became an empty string (``m`` flag for pymalloc has been |
| 23 |
removed). |
| 24 |
|
| 25 |
.. availability:: Unix. |
| 26 |
|
| 27 |
|
| 28 |
.. function:: addaudithook(hook) |
| 29 |
|
| 30 |
Append the callable *hook* to the list of active auditing hooks for the |
| 31 |
current (sub)interpreter. |
| 32 |
|
| 33 |
When an auditing event is raised through the :func:`sys.audit` function, each |
| 34 |
hook will be called in the order it was added with the event name and the |
| 35 |
tuple of arguments. Native hooks added by :c:func:`PySys_AddAuditHook` are |
| 36 |
called first, followed by hooks added in the current (sub)interpreter. Hooks |
| 37 |
can then log the event, raise an exception to abort the operation, |
| 38 |
or terminate the process entirely. |
| 39 |
|
| 40 |
Note that audit hooks are primarily for collecting information about internal |
| 41 |
or otherwise unobservable actions, whether by Python or libraries written in |
| 42 |
Python. They are not suitable for implementing a "sandbox". In particular, |
| 43 |
malicious code can trivially disable or bypass hooks added using this |
| 44 |
function. At a minimum, any security-sensitive hooks must be added using the |
| 45 |
C API :c:func:`PySys_AddAuditHook` before initialising the runtime, and any |
| 46 |
modules allowing arbitrary memory modification (such as :mod:`ctypes`) should |
| 47 |
be completely removed or closely monitored. |
| 48 |
|
| 49 |
.. audit-event:: sys.addaudithook "" sys.addaudithook |
| 50 |
|
| 51 |
Calling :func:`sys.addaudithook` will itself raise an auditing event |
| 52 |
named ``sys.addaudithook`` with no arguments. If any |
| 53 |
existing hooks raise an exception derived from :class:`RuntimeError`, the |
| 54 |
new hook will not be added and the exception suppressed. As a result, |
| 55 |
callers cannot assume that their hook has been added unless they control |
| 56 |
all existing hooks. |
| 57 |
|
| 58 |
See the :ref:`audit events table <audit-events>` for all events raised by |
| 59 |
CPython, and :pep:`578` for the original design discussion. |
| 60 |
|
| 61 |
.. versionadded:: 3.8 |
| 62 |
|
| 63 |
.. versionchanged:: 3.8.1 |
| 64 |
|
| 65 |
Exceptions derived from :class:`Exception` but not :class:`RuntimeError` |
| 66 |
are no longer suppressed. |
| 67 |
|
| 68 |
.. impl-detail:: |
| 69 |
|
| 70 |
When tracing is enabled (see :func:`settrace`), Python hooks are only |
| 71 |
traced if the callable has a ``__cantrace__`` member that is set to a |
| 72 |
true value. Otherwise, trace functions will skip the hook. |
| 73 |
|
| 74 |
|
| 75 |
.. data:: argv |
| 76 |
|
| 77 |
The list of command line arguments passed to a Python script. ``argv[0]`` is the |
| 78 |
script name (it is operating system dependent whether this is a full pathname or |
| 79 |
not). If the command was executed using the :option:`-c` command line option to |
| 80 |
the interpreter, ``argv[0]`` is set to the string ``'-c'``. If no script name |
| 81 |
was passed to the Python interpreter, ``argv[0]`` is the empty string. |
| 82 |
|
| 83 |
To loop over the standard input, or the list of files given on the |
| 84 |
command line, see the :mod:`fileinput` module. |
| 85 |
|
| 86 |
See also :data:`sys.orig_argv`. |
| 87 |
|
| 88 |
.. note:: |
| 89 |
On Unix, command line arguments are passed by bytes from OS. Python decodes |
| 90 |
them with filesystem encoding and "surrogateescape" error handler. |
| 91 |
When you need original bytes, you can get it by |
| 92 |
``[os.fsencode(arg) for arg in sys.argv]``. |
| 93 |
|
| 94 |
|
| 95 |
.. _auditing: |
| 96 |
|
| 97 |
.. function:: audit(event, *args) |
| 98 |
|
| 99 |
.. index:: single: auditing |
| 100 |
|
| 101 |
Raise an auditing event and trigger any active auditing hooks. |
| 102 |
*event* is a string identifying the event, and *args* may contain |
| 103 |
optional arguments with more information about the event. The |
| 104 |
number and types of arguments for a given event are considered a |
| 105 |
public and stable API and should not be modified between releases. |
| 106 |
|
| 107 |
For example, one auditing event is named ``os.chdir``. This event has |
| 108 |
one argument called *path* that will contain the requested new |
| 109 |
working directory. |
| 110 |
|
| 111 |
:func:`sys.audit` will call the existing auditing hooks, passing |
| 112 |
the event name and arguments, and will re-raise the first exception |
| 113 |
from any hook. In general, if an exception is raised, it should not |
| 114 |
be handled and the process should be terminated as quickly as |
| 115 |
possible. This allows hook implementations to decide how to respond |
| 116 |
to particular events: they can merely log the event or abort the |
| 117 |
operation by raising an exception. |
| 118 |
|
| 119 |
Hooks are added using the :func:`sys.addaudithook` or |
| 120 |
:c:func:`PySys_AddAuditHook` functions. |
| 121 |
|
| 122 |
The native equivalent of this function is :c:func:`PySys_Audit`. Using the |
| 123 |
native function is preferred when possible. |
| 124 |
|
| 125 |
See the :ref:`audit events table <audit-events>` for all events raised by |
| 126 |
CPython. |
| 127 |
|
| 128 |
.. versionadded:: 3.8 |
| 129 |
|
| 130 |
|
| 131 |
.. data:: base_exec_prefix |
| 132 |
|
| 133 |
Equivalent to :data:`exec_prefix`, but referring to the base Python installation. |
| 134 |
|
| 135 |
When running under :ref:`sys-path-init-virtual-environments`, |
| 136 |
:data:`exec_prefix` gets overwritten to the virtual environment prefix. |
| 137 |
:data:`base_exec_prefix`, conversely, does not change, and always points to |
| 138 |
the base Python installation. |
| 139 |
Refer to :ref:`sys-path-init-virtual-environments` for more information. |
| 140 |
|
| 141 |
.. versionadded:: 3.3 |
| 142 |
|
| 143 |
|
| 144 |
.. data:: base_prefix |
| 145 |
|
| 146 |
Equivalent to :data:`prefix`, but referring to the base Python installation. |
| 147 |
|
| 148 |
When running under :ref:`virtual environment <venv-def>`, |
| 149 |
:data:`prefix` gets overwritten to the virtual environment prefix. |
| 150 |
:data:`base_prefix`, conversely, does not change, and always points to |
| 151 |
the base Python installation. |
| 152 |
Refer to :ref:`sys-path-init-virtual-environments` for more information. |
| 153 |
|
| 154 |
.. versionadded:: 3.3 |
| 155 |
|
| 156 |
|
| 157 |
.. data:: byteorder |
| 158 |
|
| 159 |
An indicator of the native byte order. This will have the value ``'big'`` on |
| 160 |
big-endian (most-significant byte first) platforms, and ``'little'`` on |
| 161 |
little-endian (least-significant byte first) platforms. |
| 162 |
|
| 163 |
|
| 164 |
.. data:: builtin_module_names |
| 165 |
|
| 166 |
A tuple of strings containing the names of all modules that are compiled into this |
| 167 |
Python interpreter. (This information is not available in any other way --- |
| 168 |
``modules.keys()`` only lists the imported modules.) |
| 169 |
|
| 170 |
See also the :data:`sys.stdlib_module_names` list. |
| 171 |
|
| 172 |
|
| 173 |
.. function:: call_tracing(func, args) |
| 174 |
|
| 175 |
Call ``func(*args)``, while tracing is enabled. The tracing state is saved, |
| 176 |
and restored afterwards. This is intended to be called from a debugger from |
| 177 |
a checkpoint, to recursively debug or profile some other code. |
| 178 |
|
| 179 |
Tracing is suspended while calling a tracing function set by |
| 180 |
:func:`settrace` or :func:`setprofile` to avoid infinite recursion. |
| 181 |
:func:`!call_tracing` enables explicit recursion of the tracing function. |
| 182 |
|
| 183 |
|
| 184 |
.. data:: copyright |
| 185 |
|
| 186 |
A string containing the copyright pertaining to the Python interpreter. |
| 187 |
|
| 188 |
|
| 189 |
.. function:: _clear_type_cache() |
| 190 |
|
| 191 |
Clear the internal type cache. The type cache is used to speed up attribute |
| 192 |
and method lookups. Use the function *only* to drop unnecessary references |
| 193 |
during reference leak debugging. |
| 194 |
|
| 195 |
This function should be used for internal and specialized purposes only. |
| 196 |
|
| 197 |
.. deprecated:: 3.13 |
| 198 |
Use the more general :func:`_clear_internal_caches` function instead. |
| 199 |
|
| 200 |
|
| 201 |
.. function:: _clear_internal_caches() |
| 202 |
|
| 203 |
Clear all internal performance-related caches. Use this function *only* to |
| 204 |
release unnecessary references and memory blocks when hunting for leaks. |
| 205 |
|
| 206 |
.. versionadded:: 3.13 |
| 207 |
|
| 208 |
|
| 209 |
.. function:: _current_frames() |
| 210 |
|
| 211 |
Return a dictionary mapping each thread's identifier to the topmost stack frame |
| 212 |
currently active in that thread at the time the function is called. Note that |
| 213 |
functions in the :mod:`traceback` module can build the call stack given such a |
| 214 |
frame. |
| 215 |
|
| 216 |
This is most useful for debugging deadlock: this function does not require the |
| 217 |
deadlocked threads' cooperation, and such threads' call stacks are frozen for as |
| 218 |
long as they remain deadlocked. The frame returned for a non-deadlocked thread |
| 219 |
may bear no relationship to that thread's current activity by the time calling |
| 220 |
code examines the frame. |
| 221 |
|
| 222 |
This function should be used for internal and specialized purposes only. |
| 223 |
|
| 224 |
.. audit-event:: sys._current_frames "" sys._current_frames |
| 225 |
|
| 226 |
.. function:: _current_exceptions() |
| 227 |
|
| 228 |
Return a dictionary mapping each thread's identifier to the topmost exception |
| 229 |
currently active in that thread at the time the function is called. |
| 230 |
If a thread is not currently handling an exception, it is not included in |
| 231 |
the result dictionary. |
| 232 |
|
| 233 |
This is most useful for statistical profiling. |
| 234 |
|
| 235 |
This function should be used for internal and specialized purposes only. |
| 236 |
|
| 237 |
.. audit-event:: sys._current_exceptions "" sys._current_exceptions |
| 238 |
|
| 239 |
.. versionchanged:: 3.12 |
| 240 |
Each value in the dictionary is now a single exception instance, rather |
| 241 |
than a 3-tuple as returned from ``sys.exc_info()``. |
| 242 |
|
| 243 |
.. function:: breakpointhook() |
| 244 |
|
| 245 |
This hook function is called by built-in :func:`breakpoint`. By default, |
| 246 |
it drops you into the :mod:`pdb` debugger, but it can be set to any other |
| 247 |
function so that you can choose which debugger gets used. |
| 248 |
|
| 249 |
The signature of this function is dependent on what it calls. For example, |
| 250 |
the default binding (e.g. ``pdb.set_trace()``) expects no arguments, but |
| 251 |
you might bind it to a function that expects additional arguments |
| 252 |
(positional and/or keyword). The built-in ``breakpoint()`` function passes |
| 253 |
its ``*args`` and ``**kws`` straight through. Whatever |
| 254 |
``breakpointhooks()`` returns is returned from ``breakpoint()``. |
| 255 |
|
| 256 |
The default implementation first consults the environment variable |
| 257 |
:envvar:`PYTHONBREAKPOINT`. If that is set to ``"0"`` then this function |
| 258 |
returns immediately; i.e. it is a no-op. If the environment variable is |
| 259 |
not set, or is set to the empty string, ``pdb.set_trace()`` is called. |
| 260 |
Otherwise this variable should name a function to run, using Python's |
| 261 |
dotted-import nomenclature, e.g. ``package.subpackage.module.function``. |
| 262 |
In this case, ``package.subpackage.module`` would be imported and the |
| 263 |
resulting module must have a callable named ``function()``. This is run, |
| 264 |
passing in ``*args`` and ``**kws``, and whatever ``function()`` returns, |
| 265 |
``sys.breakpointhook()`` returns to the built-in :func:`breakpoint` |
| 266 |
function. |
| 267 |
|
| 268 |
Note that if anything goes wrong while importing the callable named by |
| 269 |
:envvar:`PYTHONBREAKPOINT`, a :exc:`RuntimeWarning` is reported and the |
| 270 |
breakpoint is ignored. |
| 271 |
|
| 272 |
Also note that if ``sys.breakpointhook()`` is overridden programmatically, |
| 273 |
:envvar:`PYTHONBREAKPOINT` is *not* consulted. |
| 274 |
|
| 275 |
.. versionadded:: 3.7 |
| 276 |
|
| 277 |
.. function:: _debugmallocstats() |
| 278 |
|
| 279 |
Print low-level information to stderr about the state of CPython's memory |
| 280 |
allocator. |
| 281 |
|
| 282 |
If Python is :ref:`built in debug mode <debug-build>` (:option:`configure |
| 283 |
--with-pydebug option <--with-pydebug>`), it also performs some expensive |
| 284 |
internal consistency checks. |
| 285 |
|
| 286 |
.. versionadded:: 3.3 |
| 287 |
|
| 288 |
.. impl-detail:: |
| 289 |
|
| 290 |
This function is specific to CPython. The exact output format is not |
| 291 |
defined here, and may change. |
| 292 |
|
| 293 |
|
| 294 |
.. data:: dllhandle |
| 295 |
|
| 296 |
Integer specifying the handle of the Python DLL. |
| 297 |
|
| 298 |
.. availability:: Windows. |
| 299 |
|
| 300 |
|
| 301 |
.. function:: displayhook(value) |
| 302 |
|
| 303 |
If *value* is not ``None``, this function prints ``repr(value)`` to |
| 304 |
``sys.stdout``, and saves *value* in ``builtins._``. If ``repr(value)`` is |
| 305 |
not encodable to ``sys.stdout.encoding`` with ``sys.stdout.errors`` error |
| 306 |
handler (which is probably ``'strict'``), encode it to |
| 307 |
``sys.stdout.encoding`` with ``'backslashreplace'`` error handler. |
| 308 |
|
| 309 |
``sys.displayhook`` is called on the result of evaluating an :term:`expression` |
| 310 |
entered in an interactive Python session. The display of these values can be |
| 311 |
customized by assigning another one-argument function to ``sys.displayhook``. |
| 312 |
|
| 313 |
Pseudo-code:: |
| 314 |
|
| 315 |
def displayhook(value): |
| 316 |
if value is None: |
| 317 |
return |
| 318 |
# Set '_' to None to avoid recursion |
| 319 |
builtins._ = None |
| 320 |
text = repr(value) |
| 321 |
try: |
| 322 |
sys.stdout.write(text) |
| 323 |
except UnicodeEncodeError: |
| 324 |
bytes = text.encode(sys.stdout.encoding, 'backslashreplace') |
| 325 |
if hasattr(sys.stdout, 'buffer'): |
| 326 |
sys.stdout.buffer.write(bytes) |
| 327 |
else: |
| 328 |
text = bytes.decode(sys.stdout.encoding, 'strict') |
| 329 |
sys.stdout.write(text) |
| 330 |
sys.stdout.write("\n") |
| 331 |
builtins._ = value |
| 332 |
|
| 333 |
.. versionchanged:: 3.2 |
| 334 |
Use ``'backslashreplace'`` error handler on :exc:`UnicodeEncodeError`. |
| 335 |
|
| 336 |
|
| 337 |
.. data:: dont_write_bytecode |
| 338 |
|
| 339 |
If this is true, Python won't try to write ``.pyc`` files on the |
| 340 |
import of source modules. This value is initially set to ``True`` or |
| 341 |
``False`` depending on the :option:`-B` command line option and the |
| 342 |
:envvar:`PYTHONDONTWRITEBYTECODE` environment variable, but you can set it |
| 343 |
yourself to control bytecode file generation. |
| 344 |
|
| 345 |
|
| 346 |
.. data:: _emscripten_info |
| 347 |
|
| 348 |
A :term:`named tuple` holding information about the environment on the |
| 349 |
*wasm32-emscripten* platform. The named tuple is provisional and may change |
| 350 |
in the future. |
| 351 |
|
| 352 |
.. attribute:: _emscripten_info.emscripten_version |
| 353 |
|
| 354 |
Emscripten version as tuple of ints (major, minor, micro), e.g. ``(3, 1, 8)``. |
| 355 |
|
| 356 |
.. attribute:: _emscripten_info.runtime |
| 357 |
|
| 358 |
Runtime string, e.g. browser user agent, ``'Node.js v14.18.2'``, or ``'UNKNOWN'``. |
| 359 |
|
| 360 |
.. attribute:: _emscripten_info.pthreads |
| 361 |
|
| 362 |
``True`` if Python is compiled with Emscripten pthreads support. |
| 363 |
|
| 364 |
.. attribute:: _emscripten_info.shared_memory |
| 365 |
|
| 366 |
``True`` if Python is compiled with shared memory support. |
| 367 |
|
| 368 |
.. availability:: Emscripten. |
| 369 |
|
| 370 |
.. versionadded:: 3.11 |
| 371 |
|
| 372 |
|
| 373 |
.. data:: pycache_prefix |
| 374 |
|
| 375 |
If this is set (not ``None``), Python will write bytecode-cache ``.pyc`` |
| 376 |
files to (and read them from) a parallel directory tree rooted at this |
| 377 |
directory, rather than from ``__pycache__`` directories in the source code |
| 378 |
tree. Any ``__pycache__`` directories in the source code tree will be ignored |
| 379 |
and new ``.pyc`` files written within the pycache prefix. Thus if you use |
| 380 |
:mod:`compileall` as a pre-build step, you must ensure you run it with the |
| 381 |
same pycache prefix (if any) that you will use at runtime. |
| 382 |
|
| 383 |
A relative path is interpreted relative to the current working directory. |
| 384 |
|
| 385 |
This value is initially set based on the value of the :option:`-X` |
| 386 |
``pycache_prefix=PATH`` command-line option or the |
| 387 |
:envvar:`PYTHONPYCACHEPREFIX` environment variable (command-line takes |
| 388 |
precedence). If neither are set, it is ``None``. |
| 389 |
|
| 390 |
.. versionadded:: 3.8 |
| 391 |
|
| 392 |
|
| 393 |
.. function:: excepthook(type, value, traceback) |
| 394 |
|
| 395 |
This function prints out a given traceback and exception to ``sys.stderr``. |
| 396 |
|
| 397 |
When an exception other than :exc:`SystemExit` is raised and uncaught, the interpreter calls |
| 398 |
``sys.excepthook`` with three arguments, the exception class, exception |
| 399 |
instance, and a traceback object. In an interactive session this happens just |
| 400 |
before control is returned to the prompt; in a Python program this happens just |
| 401 |
before the program exits. The handling of such top-level exceptions can be |
| 402 |
customized by assigning another three-argument function to ``sys.excepthook``. |
| 403 |
|
| 404 |
.. audit-event:: sys.excepthook hook,type,value,traceback sys.excepthook |
| 405 |
|
| 406 |
Raise an auditing event ``sys.excepthook`` with arguments ``hook``, |
| 407 |
``type``, ``value``, ``traceback`` when an uncaught exception occurs. |
| 408 |
If no hook has been set, ``hook`` may be ``None``. If any hook raises |
| 409 |
an exception derived from :class:`RuntimeError` the call to the hook will |
| 410 |
be suppressed. Otherwise, the audit hook exception will be reported as |
| 411 |
unraisable and ``sys.excepthook`` will be called. |
| 412 |
|
| 413 |
.. seealso:: |
| 414 |
|
| 415 |
The :func:`sys.unraisablehook` function handles unraisable exceptions |
| 416 |
and the :func:`threading.excepthook` function handles exception raised |
| 417 |
by :func:`threading.Thread.run`. |
| 418 |
|
| 419 |
|
| 420 |
.. data:: __breakpointhook__ |
| 421 |
__displayhook__ |
| 422 |
__excepthook__ |
| 423 |
__unraisablehook__ |
| 424 |
|
| 425 |
These objects contain the original values of ``breakpointhook``, |
| 426 |
``displayhook``, ``excepthook``, and ``unraisablehook`` at the start of the |
| 427 |
program. They are saved so that ``breakpointhook``, ``displayhook`` and |
| 428 |
``excepthook``, ``unraisablehook`` can be restored in case they happen to |
| 429 |
get replaced with broken or alternative objects. |
| 430 |
|
| 431 |
.. versionadded:: 3.7 |
| 432 |
__breakpointhook__ |
| 433 |
|
| 434 |
.. versionadded:: 3.8 |
| 435 |
__unraisablehook__ |
| 436 |
|
| 437 |
|
| 438 |
.. function:: exception() |
| 439 |
|
| 440 |
This function, when called while an exception handler is executing (such as |
| 441 |
an ``except`` or ``except*`` clause), returns the exception instance that |
| 442 |
was caught by this handler. When exception handlers are nested within one |
| 443 |
another, only the exception handled by the innermost handler is accessible. |
| 444 |
|
| 445 |
If no exception handler is executing, this function returns ``None``. |
| 446 |
|
| 447 |
.. versionadded:: 3.11 |
| 448 |
|
| 449 |
|
| 450 |
.. function:: exc_info() |
| 451 |
|
| 452 |
This function returns the old-style representation of the handled |
| 453 |
exception. If an exception ``e`` is currently handled (so |
| 454 |
:func:`exception` would return ``e``), :func:`exc_info` returns the |
| 455 |
tuple ``(type(e), e, e.__traceback__)``. |
| 456 |
That is, a tuple containing the type of the exception (a subclass of |
| 457 |
:exc:`BaseException`), the exception itself, and a :ref:`traceback |
| 458 |
object <traceback-objects>` which typically encapsulates the call |
| 459 |
stack at the point where the exception last occurred. |
| 460 |
|
| 461 |
.. index:: pair: object; traceback |
| 462 |
|
| 463 |
If no exception is being handled anywhere on the stack, this function |
| 464 |
return a tuple containing three ``None`` values. |
| 465 |
|
| 466 |
.. versionchanged:: 3.11 |
| 467 |
The ``type`` and ``traceback`` fields are now derived from the ``value`` |
| 468 |
(the exception instance), so when an exception is modified while it is |
| 469 |
being handled, the changes are reflected in the results of subsequent |
| 470 |
calls to :func:`exc_info`. |
| 471 |
|
| 472 |
.. data:: exec_prefix |
| 473 |
|
| 474 |
A string giving the site-specific directory prefix where the platform-dependent |
| 475 |
Python files are installed; by default, this is also ``'/usr/local'``. This can |
| 476 |
be set at build time with the ``--exec-prefix`` argument to the |
| 477 |
:program:`configure` script. Specifically, all configuration files (e.g. the |
| 478 |
:file:`pyconfig.h` header file) are installed in the directory |
| 479 |
:file:`{exec_prefix}/lib/python{X.Y}/config`, and shared library modules are |
| 480 |
installed in :file:`{exec_prefix}/lib/python{X.Y}/lib-dynload`, where *X.Y* |
| 481 |
is the version number of Python, for example ``3.2``. |
| 482 |
|
| 483 |
.. note:: |
| 484 |
|
| 485 |
If a :ref:`virtual environment <venv-def>` is in effect, this :data:`exec_prefix` |
| 486 |
will point to the virtual environment. The value for the Python installation |
| 487 |
will still be available, via :data:`base_exec_prefix`. |
| 488 |
Refer to :ref:`sys-path-init-virtual-environments` for more information. |
| 489 |
|
| 490 |
.. versionchanged:: 3.14 |
| 491 |
|
| 492 |
When running under a :ref:`virtual environment <venv-def>`, |
| 493 |
:data:`prefix` and :data:`exec_prefix` are now set to the virtual |
| 494 |
environment prefix by the :ref:`path initialization <sys-path-init>`, |
| 495 |
instead of :mod:`site`. This means that :data:`prefix` and |
| 496 |
:data:`exec_prefix` always point to the virtual environment, even when |
| 497 |
:mod:`site` is disabled (:option:`-S`). |
| 498 |
|
| 499 |
.. data:: executable |
| 500 |
|
| 501 |
A string giving the absolute path of the executable binary for the Python |
| 502 |
interpreter, on systems where this makes sense. If Python is unable to retrieve |
| 503 |
the real path to its executable, :data:`sys.executable` will be an empty string |
| 504 |
or ``None``. |
| 505 |
|
| 506 |
|
| 507 |
.. function:: exit([arg]) |
| 508 |
|
| 509 |
Raise a :exc:`SystemExit` exception, signaling an intention to exit the interpreter. |
| 510 |
|
| 511 |
The optional argument *arg* can be an integer giving the exit status |
| 512 |
(defaulting to zero), or another type of object. If it is an integer, zero |
| 513 |
is considered "successful termination" and any nonzero value is considered |
| 514 |
"abnormal termination" by shells and the like. Most systems require it to be |
| 515 |
in the range 0--127, and produce undefined results otherwise. Some systems |
| 516 |
have a convention for assigning specific meanings to specific exit codes, but |
| 517 |
these are generally underdeveloped; Unix programs generally use 2 for command |
| 518 |
line syntax errors and 1 for all other kinds of errors. If another type of |
| 519 |
object is passed, ``None`` is equivalent to passing zero, and any other |
| 520 |
object is printed to :data:`stderr` and results in an exit code of 1. In |
| 521 |
particular, ``sys.exit("some error message")`` is a quick way to exit a |
| 522 |
program when an error occurs. |
| 523 |
|
| 524 |
Since :func:`exit` ultimately "only" raises an exception, it will only exit |
| 525 |
the process when called from the main thread, and the exception is not |
| 526 |
intercepted. Cleanup actions specified by finally clauses of :keyword:`try` statements |
| 527 |
are honored, and it is possible to intercept the exit attempt at an outer level. |
| 528 |
|
| 529 |
.. versionchanged:: 3.6 |
| 530 |
If an error occurs in the cleanup after the Python interpreter |
| 531 |
has caught :exc:`SystemExit` (such as an error flushing buffered data |
| 532 |
in the standard streams), the exit status is changed to 120. |
| 533 |
|
| 534 |
|
| 535 |
.. data:: flags |
| 536 |
|
| 537 |
The :term:`named tuple` *flags* exposes the status of command line |
| 538 |
flags. Flags should only be accessed only by name and not by index. The |
| 539 |
attributes are read only. |
| 540 |
|
| 541 |
.. list-table:: |
| 542 |
|
| 543 |
* - .. attribute:: flags.debug |
| 544 |
- :option:`-d` |
| 545 |
|
| 546 |
* - .. attribute:: flags.inspect |
| 547 |
- :option:`-i` |
| 548 |
|
| 549 |
* - .. attribute:: flags.interactive |
| 550 |
- :option:`-i` |
| 551 |
|
| 552 |
* - .. attribute:: flags.isolated |
| 553 |
- :option:`-I` |
| 554 |
|
| 555 |
* - .. attribute:: flags.optimize |
| 556 |
- :option:`-O` or :option:`-OO` |
| 557 |
|
| 558 |
* - .. attribute:: flags.dont_write_bytecode |
| 559 |
- :option:`-B` |
| 560 |
|
| 561 |
* - .. attribute:: flags.no_user_site |
| 562 |
- :option:`-s` |
| 563 |
|
| 564 |
* - .. attribute:: flags.no_site |
| 565 |
- :option:`-S` |
| 566 |
|
| 567 |
* - .. attribute:: flags.ignore_environment |
| 568 |
- :option:`-E` |
| 569 |
|
| 570 |
* - .. attribute:: flags.verbose |
| 571 |
- :option:`-v` |
| 572 |
|
| 573 |
* - .. attribute:: flags.bytes_warning |
| 574 |
- :option:`-b` |
| 575 |
|
| 576 |
* - .. attribute:: flags.quiet |
| 577 |
- :option:`-q` |
| 578 |
|
| 579 |
* - .. attribute:: flags.hash_randomization |
| 580 |
- :option:`-R` |
| 581 |
|
| 582 |
* - .. attribute:: flags.dev_mode |
| 583 |
- :option:`-X dev <-X>` (:ref:`Python Development Mode <devmode>`) |
| 584 |
|
| 585 |
* - .. attribute:: flags.utf8_mode |
| 586 |
- :option:`-X utf8 <-X>` |
| 587 |
|
| 588 |
* - .. attribute:: flags.safe_path |
| 589 |
- :option:`-P` |
| 590 |
|
| 591 |
* - .. attribute:: flags.int_max_str_digits |
| 592 |
- :option:`-X int_max_str_digits <-X>` |
| 593 |
(:ref:`integer string conversion length limitation <int_max_str_digits>`) |
| 594 |
|
| 595 |
* - .. attribute:: flags.warn_default_encoding |
| 596 |
- :option:`-X warn_default_encoding <-X>` |
| 597 |
|
| 598 |
* - .. attribute:: flags.gil |
| 599 |
- :option:`-X gil <-X>` and :envvar:`PYTHON_GIL` |
| 600 |
|
| 601 |
* - .. attribute:: flags.thread_inherit_context |
| 602 |
- :option:`-X thread_inherit_context <-X>` and |
| 603 |
:envvar:`PYTHON_THREAD_INHERIT_CONTEXT` |
| 604 |
|
| 605 |
* - .. attribute:: flags.context_aware_warnings |
| 606 |
- :option:`-X context_aware_warnings <-X>` and |
| 607 |
:envvar:`PYTHON_CONTEXT_AWARE_WARNINGS` |
| 608 |
|
| 609 |
|
| 610 |
.. versionchanged:: 3.2 |
| 611 |
Added ``quiet`` attribute for the new :option:`-q` flag. |
| 612 |
|
| 613 |
.. versionadded:: 3.2.3 |
| 614 |
The ``hash_randomization`` attribute. |
| 615 |
|
| 616 |
.. versionchanged:: 3.3 |
| 617 |
Removed obsolete ``division_warning`` attribute. |
| 618 |
|
| 619 |
.. versionchanged:: 3.4 |
| 620 |
Added ``isolated`` attribute for :option:`-I` ``isolated`` flag. |
| 621 |
|
| 622 |
.. versionchanged:: 3.7 |
| 623 |
Added the ``dev_mode`` attribute for the new :ref:`Python Development |
| 624 |
Mode <devmode>` and the ``utf8_mode`` attribute for the new :option:`-X` |
| 625 |
``utf8`` flag. |
| 626 |
|
| 627 |
.. versionchanged:: 3.10 |
| 628 |
Added ``warn_default_encoding`` attribute for :option:`-X` ``warn_default_encoding`` flag. |
| 629 |
|
| 630 |
.. versionchanged:: 3.11 |
| 631 |
Added the ``safe_path`` attribute for :option:`-P` option. |
| 632 |
|
| 633 |
.. versionchanged:: 3.11 |
| 634 |
Added the ``int_max_str_digits`` attribute. |
| 635 |
|
| 636 |
.. versionchanged:: 3.13 |
| 637 |
Added the ``gil`` attribute. |
| 638 |
|
| 639 |
.. versionchanged:: 3.14 |
| 640 |
Added the ``thread_inherit_context`` attribute. |
| 641 |
|
| 642 |
.. versionchanged:: 3.14 |
| 643 |
Added the ``context_aware_warnings`` attribute. |
| 644 |
|
| 645 |
|
| 646 |
.. data:: float_info |
| 647 |
|
| 648 |
A :term:`named tuple` holding information about the float type. It |
| 649 |
contains low level information about the precision and internal |
| 650 |
representation. The values correspond to the various floating-point |
| 651 |
constants defined in the standard header file :file:`float.h` for the 'C' |
| 652 |
programming language; see section 5.2.4.2.2 of the 1999 ISO/IEC C standard |
| 653 |
[C99]_, 'Characteristics of floating types', for details. |
| 654 |
|
| 655 |
.. list-table:: Attributes of the :data:`!float_info` :term:`named tuple` |
| 656 |
:header-rows: 1 |
| 657 |
|
| 658 |
* - attribute |
| 659 |
- float.h macro |
| 660 |
- explanation |
| 661 |
|
| 662 |
* - .. attribute:: float_info.epsilon |
| 663 |
- :c:macro:`!DBL_EPSILON` |
| 664 |
- difference between 1.0 and the least value greater than 1.0 that is |
| 665 |
representable as a float. |
| 666 |
|
| 667 |
See also :func:`math.ulp`. |
| 668 |
|
| 669 |
* - .. attribute:: float_info.dig |
| 670 |
- :c:macro:`!DBL_DIG` |
| 671 |
- The maximum number of decimal digits that can be faithfully |
| 672 |
represented in a float; see below. |
| 673 |
|
| 674 |
* - .. attribute:: float_info.mant_dig |
| 675 |
- :c:macro:`!DBL_MANT_DIG` |
| 676 |
- Float precision: the number of base-``radix`` digits in the |
| 677 |
significand of a float. |
| 678 |
|
| 679 |
* - .. attribute:: float_info.max |
| 680 |
- :c:macro:`!DBL_MAX` |
| 681 |
- The maximum representable positive finite float. |
| 682 |
|
| 683 |
* - .. attribute:: float_info.max_exp |
| 684 |
- :c:macro:`!DBL_MAX_EXP` |
| 685 |
- The maximum integer *e* such that ``radix**(e-1)`` is a representable |
| 686 |
finite float. |
| 687 |
|
| 688 |
* - .. attribute:: float_info.max_10_exp |
| 689 |
- :c:macro:`!DBL_MAX_10_EXP` |
| 690 |
- The maximum integer *e* such that ``10**e`` is in the range of |
| 691 |
representable finite floats. |
| 692 |
|
| 693 |
* - .. attribute:: float_info.min |
| 694 |
- :c:macro:`!DBL_MIN` |
| 695 |
- The minimum representable positive *normalized* float. |
| 696 |
|
| 697 |
Use :func:`math.ulp(0.0) <math.ulp>` to get the smallest positive |
| 698 |
*denormalized* representable float. |
| 699 |
|
| 700 |
* - .. attribute:: float_info.min_exp |
| 701 |
- :c:macro:`!DBL_MIN_EXP` |
| 702 |
- The minimum integer *e* such that ``radix**(e-1)`` is a normalized |
| 703 |
float. |
| 704 |
|
| 705 |
* - .. attribute:: float_info.min_10_exp |
| 706 |
- :c:macro:`!DBL_MIN_10_EXP` |
| 707 |
- The minimum integer *e* such that ``10**e`` is a normalized float. |
| 708 |
|
| 709 |
* - .. attribute:: float_info.radix |
| 710 |
- :c:macro:`!FLT_RADIX` |
| 711 |
- The radix of exponent representation. |
| 712 |
|
| 713 |
* - .. attribute:: float_info.rounds |
| 714 |
- :c:macro:`!FLT_ROUNDS` |
| 715 |
- An integer representing the rounding mode for floating-point arithmetic. |
| 716 |
This reflects the value of the system :c:macro:`!FLT_ROUNDS` macro |
| 717 |
at interpreter startup time: |
| 718 |
|
| 719 |
* ``-1``: indeterminable |
| 720 |
* ``0``: toward zero |
| 721 |
* ``1``: to nearest |
| 722 |
* ``2``: toward positive infinity |
| 723 |
* ``3``: toward negative infinity |
| 724 |
|
| 725 |
All other values for :c:macro:`!FLT_ROUNDS` characterize |
| 726 |
implementation-defined rounding behavior. |
| 727 |
|
| 728 |
The attribute :attr:`sys.float_info.dig` needs further explanation. If |
| 729 |
``s`` is any string representing a decimal number with at most |
| 730 |
:attr:`!sys.float_info.dig` significant digits, then converting ``s`` to a |
| 731 |
float and back again will recover a string representing the same decimal |
| 732 |
value:: |
| 733 |
|
| 734 |
>>> import sys |
| 735 |
>>> sys.float_info.dig |
| 736 |
15 |
| 737 |
>>> s = '3.14159265358979' # decimal string with 15 significant digits |
| 738 |
>>> format(float(s), '.15g') # convert to float and back -> same value |
| 739 |
'3.14159265358979' |
| 740 |
|
| 741 |
But for strings with more than :attr:`sys.float_info.dig` significant digits, |
| 742 |
this isn't always true:: |
| 743 |
|
| 744 |
>>> s = '9876543211234567' # 16 significant digits is too many! |
| 745 |
>>> format(float(s), '.16g') # conversion changes value |
| 746 |
'9876543211234568' |
| 747 |
|
| 748 |
.. data:: float_repr_style |
| 749 |
|
| 750 |
A string indicating how the :func:`repr` function behaves for |
| 751 |
floats. If the string has value ``'short'`` then for a finite |
| 752 |
float ``x``, ``repr(x)`` aims to produce a short string with the |
| 753 |
property that ``float(repr(x)) == x``. This is the usual behaviour |
| 754 |
in Python 3.1 and later. Otherwise, ``float_repr_style`` has value |
| 755 |
``'legacy'`` and ``repr(x)`` behaves in the same way as it did in |
| 756 |
versions of Python prior to 3.1. |
| 757 |
|
| 758 |
.. versionadded:: 3.1 |
| 759 |
|
| 760 |
|
| 761 |
.. function:: getallocatedblocks() |
| 762 |
|
| 763 |
Return the number of memory blocks currently allocated by the interpreter, |
| 764 |
regardless of their size. This function is mainly useful for tracking |
| 765 |
and debugging memory leaks. Because of the interpreter's internal |
| 766 |
caches, the result can vary from call to call; you may have to call |
| 767 |
:func:`_clear_internal_caches` and :func:`gc.collect` to get more |
| 768 |
predictable results. |
| 769 |
|
| 770 |
If a Python build or implementation cannot reasonably compute this |
| 771 |
information, :func:`getallocatedblocks` is allowed to return 0 instead. |
| 772 |
|
| 773 |
.. versionadded:: 3.4 |
| 774 |
|
| 775 |
|
| 776 |
.. function:: getunicodeinternedsize() |
| 777 |
|
| 778 |
Return the number of unicode objects that have been interned. |
| 779 |
|
| 780 |
.. versionadded:: 3.12 |
| 781 |
|
| 782 |
|
| 783 |
.. function:: getandroidapilevel() |
| 784 |
|
| 785 |
Return the build-time API level of Android as an integer. This represents the |
| 786 |
minimum version of Android this build of Python can run on. For runtime |
| 787 |
version information, see :func:`platform.android_ver`. |
| 788 |
|
| 789 |
.. availability:: Android. |
| 790 |
|
| 791 |
.. versionadded:: 3.7 |
| 792 |
|
| 793 |
|
| 794 |
.. function:: getdefaultencoding() |
| 795 |
|
| 796 |
Return ``'utf-8'``. This is the name of the default string encoding, used |
| 797 |
in methods like :meth:`str.encode`. |
| 798 |
|
| 799 |
|
| 800 |
.. function:: getdlopenflags() |
| 801 |
|
| 802 |
Return the current value of the flags that are used for |
| 803 |
:c:func:`dlopen` calls. Symbolic names for the flag values can be |
| 804 |
found in the :mod:`os` module (:samp:`RTLD_{xxx}` constants, e.g. |
| 805 |
:const:`os.RTLD_LAZY`). |
| 806 |
|
| 807 |
.. availability:: Unix. |
| 808 |
|
| 809 |
|
| 810 |
.. function:: getfilesystemencoding() |
| 811 |
|
| 812 |
Get the :term:`filesystem encoding <filesystem encoding and error handler>`: |
| 813 |
the encoding used with the :term:`filesystem error handler <filesystem |
| 814 |
encoding and error handler>` to convert between Unicode filenames and bytes |
| 815 |
filenames. The filesystem error handler is returned from |
| 816 |
:func:`getfilesystemencodeerrors`. |
| 817 |
|
| 818 |
For best compatibility, str should be used for filenames in all cases, |
| 819 |
although representing filenames as bytes is also supported. Functions |
| 820 |
accepting or returning filenames should support either str or bytes and |
| 821 |
internally convert to the system's preferred representation. |
| 822 |
|
| 823 |
:func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that |
| 824 |
the correct encoding and errors mode are used. |
| 825 |
|
| 826 |
The :term:`filesystem encoding and error handler` are configured at Python |
| 827 |
startup by the :c:func:`PyConfig_Read` function: see |
| 828 |
:c:member:`~PyConfig.filesystem_encoding` and |
| 829 |
:c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`. |
| 830 |
|
| 831 |
.. versionchanged:: 3.2 |
| 832 |
:func:`getfilesystemencoding` result cannot be ``None`` anymore. |
| 833 |
|
| 834 |
.. versionchanged:: 3.6 |
| 835 |
Windows is no longer guaranteed to return ``'mbcs'``. See :pep:`529` |
| 836 |
and :func:`_enablelegacywindowsfsencoding` for more information. |
| 837 |
|
| 838 |
.. versionchanged:: 3.7 |
| 839 |
Return ``'utf-8'`` if the :ref:`Python UTF-8 Mode <utf8-mode>` is |
| 840 |
enabled. |
| 841 |
|
| 842 |
|
| 843 |
.. function:: getfilesystemencodeerrors() |
| 844 |
|
| 845 |
Get the :term:`filesystem error handler <filesystem encoding and error |
| 846 |
handler>`: the error handler used with the :term:`filesystem encoding |
| 847 |
<filesystem encoding and error handler>` to convert between Unicode |
| 848 |
filenames and bytes filenames. The filesystem encoding is returned from |
| 849 |
:func:`getfilesystemencoding`. |
| 850 |
|
| 851 |
:func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that |
| 852 |
the correct encoding and errors mode are used. |
| 853 |
|
| 854 |
The :term:`filesystem encoding and error handler` are configured at Python |
| 855 |
startup by the :c:func:`PyConfig_Read` function: see |
| 856 |
:c:member:`~PyConfig.filesystem_encoding` and |
| 857 |
:c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`. |
| 858 |
|
| 859 |
.. versionadded:: 3.6 |
| 860 |
|
| 861 |
.. function:: get_int_max_str_digits() |
| 862 |
|
| 863 |
Returns the current value for the :ref:`integer string conversion length |
| 864 |
limitation <int_max_str_digits>`. See also :func:`set_int_max_str_digits`. |
| 865 |
|
| 866 |
.. versionadded:: 3.11 |
| 867 |
|
| 868 |
.. function:: getrefcount(object) |
| 869 |
|
| 870 |
Return the reference count of the *object*. The count returned is generally one |
| 871 |
higher than you might expect, because it includes the (temporary) reference as |
| 872 |
an argument to :func:`getrefcount`. |
| 873 |
|
| 874 |
Note that the returned value may not actually reflect how many |
| 875 |
references to the object are actually held. For example, some |
| 876 |
objects are :term:`immortal` and have a very high refcount that does not |
| 877 |
reflect the actual number of references. Consequently, do not rely |
| 878 |
on the returned value to be accurate, other than a value of 0 or 1. |
| 879 |
|
| 880 |
.. impl-detail:: |
| 881 |
|
| 882 |
:term:`Immortal <immortal>` objects with a large reference count can be |
| 883 |
identified via :func:`_is_immortal`. |
| 884 |
|
| 885 |
.. versionchanged:: 3.12 |
| 886 |
Immortal objects have very large refcounts that do not match |
| 887 |
the actual number of references to the object. |
| 888 |
|
| 889 |
.. function:: getrecursionlimit() |
| 890 |
|
| 891 |
Return the current value of the recursion limit, the maximum depth of the Python |
| 892 |
interpreter stack. This limit prevents infinite recursion from causing an |
| 893 |
overflow of the C stack and crashing Python. It can be set by |
| 894 |
:func:`setrecursionlimit`. |
| 895 |
|
| 896 |
|
| 897 |
.. function:: getsizeof(object[, default]) |
| 898 |
|
| 899 |
Return the size of an object in bytes. The object can be any type of |
| 900 |
object. All built-in objects will return correct results, but this |
| 901 |
does not have to hold true for third-party extensions as it is implementation |
| 902 |
specific. |
| 903 |
|
| 904 |
Only the memory consumption directly attributed to the object is |
| 905 |
accounted for, not the memory consumption of objects it refers to. |
| 906 |
|
| 907 |
If given, *default* will be returned if the object does not provide means to |
| 908 |
retrieve the size. Otherwise a :exc:`TypeError` will be raised. |
| 909 |
|
| 910 |
:func:`getsizeof` calls the object's ``__sizeof__`` method and adds an |
| 911 |
additional garbage collector overhead if the object is managed by the garbage |
| 912 |
collector. |
| 913 |
|
| 914 |
See `recursive sizeof recipe <https://code.activestate.com/recipes/577504-compute-memory-footprint-of-an-object-and-its-cont/>`_ |
| 915 |
for an example of using :func:`getsizeof` recursively to find the size of |
| 916 |
containers and all their contents. |
| 917 |
|
| 918 |
.. function:: getswitchinterval() |
| 919 |
|
| 920 |
Return the interpreter's "thread switch interval" in seconds; see |
| 921 |
:func:`setswitchinterval`. |
| 922 |
|
| 923 |
.. versionadded:: 3.2 |
| 924 |
|
| 925 |
|
| 926 |
.. function:: _getframe([depth]) |
| 927 |
|
| 928 |
Return a frame object from the call stack. If optional integer *depth* is |
| 929 |
given, return the frame object that many calls below the top of the stack. If |
| 930 |
that is deeper than the call stack, :exc:`ValueError` is raised. The default |
| 931 |
for *depth* is zero, returning the frame at the top of the call stack. |
| 932 |
|
| 933 |
.. audit-event:: sys._getframe frame sys._getframe |
| 934 |
|
| 935 |
.. impl-detail:: |
| 936 |
|
| 937 |
This function should be used for internal and specialized purposes only. |
| 938 |
It is not guaranteed to exist in all implementations of Python. |
| 939 |
|
| 940 |
|
| 941 |
.. function:: _getframemodulename([depth]) |
| 942 |
|
| 943 |
Return the name of a module from the call stack. If optional integer *depth* |
| 944 |
is given, return the module that many calls below the top of the stack. If |
| 945 |
that is deeper than the call stack, or if the module is unidentifiable, |
| 946 |
``None`` is returned. The default for *depth* is zero, returning the |
| 947 |
module at the top of the call stack. |
| 948 |
|
| 949 |
.. audit-event:: sys._getframemodulename depth sys._getframemodulename |
| 950 |
|
| 951 |
.. impl-detail:: |
| 952 |
|
| 953 |
This function should be used for internal and specialized purposes only. |
| 954 |
It is not guaranteed to exist in all implementations of Python. |
| 955 |
|
| 956 |
.. versionadded:: 3.12 |
| 957 |
|
| 958 |
|
| 959 |
.. function:: getobjects(limit[, type]) |
| 960 |
|
| 961 |
This function only exists if CPython was built using the |
| 962 |
specialized configure option :option:`--with-trace-refs`. |
| 963 |
It is intended only for debugging garbage-collection issues. |
| 964 |
|
| 965 |
Return a list of up to *limit* dynamically allocated Python objects. |
| 966 |
If *type* is given, only objects of that exact type (not subtypes) |
| 967 |
are included. |
| 968 |
|
| 969 |
Objects from the list are not safe to use. |
| 970 |
Specifically, the result will include objects from all interpreters that |
| 971 |
share their object allocator state (that is, ones created with |
| 972 |
:c:member:`PyInterpreterConfig.use_main_obmalloc` set to 1 |
| 973 |
or using :c:func:`Py_NewInterpreter`, and the |
| 974 |
:ref:`main interpreter <sub-interpreter-support>`). |
| 975 |
Mixing objects from different interpreters may lead to crashes |
| 976 |
or other unexpected behavior. |
| 977 |
|
| 978 |
.. impl-detail:: |
| 979 |
|
| 980 |
This function should be used for specialized purposes only. |
| 981 |
It is not guaranteed to exist in all implementations of Python. |
| 982 |
|
| 983 |
.. versionchanged:: 3.14 |
| 984 |
|
| 985 |
The result may include objects from other interpreters. |
| 986 |
|
| 987 |
|
| 988 |
.. function:: getprofile() |
| 989 |
|
| 990 |
.. index:: |
| 991 |
single: profile function |
| 992 |
single: profiler |
| 993 |
|
| 994 |
Get the profiler function as set by :func:`setprofile`. |
| 995 |
|
| 996 |
|
| 997 |
.. function:: gettrace() |
| 998 |
|
| 999 |
.. index:: |
| 1000 |
single: trace function |
| 1001 |
single: debugger |
| 1002 |
|
| 1003 |
Get the trace function as set by :func:`settrace`. |
| 1004 |
|
| 1005 |
.. impl-detail:: |
| 1006 |
|
| 1007 |
The :func:`gettrace` function is intended only for implementing debuggers, |
| 1008 |
profilers, coverage tools and the like. Its behavior is part of the |
| 1009 |
implementation platform, rather than part of the language definition, and |
| 1010 |
thus may not be available in all Python implementations. |
| 1011 |
|
| 1012 |
|
| 1013 |
.. function:: getwindowsversion() |
| 1014 |
|
| 1015 |
Return a named tuple describing the Windows version |
| 1016 |
currently running. The named elements are *major*, *minor*, |
| 1017 |
*build*, *platform*, *service_pack*, *service_pack_minor*, |
| 1018 |
*service_pack_major*, *suite_mask*, *product_type* and |
| 1019 |
*platform_version*. *service_pack* contains a string, |
| 1020 |
*platform_version* a 3-tuple and all other values are |
| 1021 |
integers. The components can also be accessed by name, so |
| 1022 |
``sys.getwindowsversion()[0]`` is equivalent to |
| 1023 |
``sys.getwindowsversion().major``. For compatibility with prior |
| 1024 |
versions, only the first 5 elements are retrievable by indexing. |
| 1025 |
|
| 1026 |
*platform* will be ``2`` (VER_PLATFORM_WIN32_NT). |
| 1027 |
|
| 1028 |
*product_type* may be one of the following values: |
| 1029 |
|
| 1030 |
+---------------------------------------+---------------------------------+ |
| 1031 |
| Constant | Meaning | |
| 1032 |
+=======================================+=================================+ |
| 1033 |
| ``1`` (VER_NT_WORKSTATION) | The system is a workstation. | |
| 1034 |
+---------------------------------------+---------------------------------+ |
| 1035 |
| ``2`` (VER_NT_DOMAIN_CONTROLLER) | The system is a domain | |
| 1036 |
| | controller. | |
| 1037 |
+---------------------------------------+---------------------------------+ |
| 1038 |
| ``3`` (VER_NT_SERVER) | The system is a server, but not | |
| 1039 |
| | a domain controller. | |
| 1040 |
+---------------------------------------+---------------------------------+ |
| 1041 |
|
| 1042 |
This function wraps the Win32 :c:func:`!GetVersionEx` function; see the |
| 1043 |
Microsoft documentation on :c:func:`!OSVERSIONINFOEX` for more information |
| 1044 |
about these fields. |
| 1045 |
|
| 1046 |
*platform_version* returns the major version, minor version and |
| 1047 |
build number of the current operating system, rather than the version that |
| 1048 |
is being emulated for the process. It is intended for use in logging rather |
| 1049 |
than for feature detection. |
| 1050 |
|
| 1051 |
.. note:: |
| 1052 |
*platform_version* derives the version from kernel32.dll which can be of a different |
| 1053 |
version than the OS version. Please use :mod:`platform` module for achieving accurate |
| 1054 |
OS version. |
| 1055 |
|
| 1056 |
.. availability:: Windows. |
| 1057 |
|
| 1058 |
.. versionchanged:: 3.2 |
| 1059 |
Changed to a named tuple and added *service_pack_minor*, |
| 1060 |
*service_pack_major*, *suite_mask*, and *product_type*. |
| 1061 |
|
| 1062 |
.. versionchanged:: 3.6 |
| 1063 |
Added *platform_version* |
| 1064 |
|
| 1065 |
|
| 1066 |
.. function:: get_asyncgen_hooks() |
| 1067 |
|
| 1068 |
Returns an *asyncgen_hooks* object, which is similar to a |
| 1069 |
:class:`~collections.namedtuple` of the form ``(firstiter, finalizer)``, |
| 1070 |
where *firstiter* and *finalizer* are expected to be either ``None`` or |
| 1071 |
functions which take an :term:`asynchronous generator iterator` as an |
| 1072 |
argument, and are used to schedule finalization of an asynchronous |
| 1073 |
generator by an event loop. |
| 1074 |
|
| 1075 |
.. versionadded:: 3.6 |
| 1076 |
See :pep:`525` for more details. |
| 1077 |
|
| 1078 |
.. note:: |
| 1079 |
This function has been added on a provisional basis (see :pep:`411` |
| 1080 |
for details.) |
| 1081 |
|
| 1082 |
|
| 1083 |
.. function:: get_coroutine_origin_tracking_depth() |
| 1084 |
|
| 1085 |
Get the current coroutine origin tracking depth, as set by |
| 1086 |
:func:`set_coroutine_origin_tracking_depth`. |
| 1087 |
|
| 1088 |
.. versionadded:: 3.7 |
| 1089 |
|
| 1090 |
.. note:: |
| 1091 |
This function has been added on a provisional basis (see :pep:`411` |
| 1092 |
for details.) Use it only for debugging purposes. |
| 1093 |
|
| 1094 |
|
| 1095 |
.. data:: hash_info |
| 1096 |
|
| 1097 |
A :term:`named tuple` giving parameters of the numeric hash |
| 1098 |
implementation. For more details about hashing of numeric types, see |
| 1099 |
:ref:`numeric-hash`. |
| 1100 |
|
| 1101 |
.. attribute:: hash_info.width |
| 1102 |
|
| 1103 |
The width in bits used for hash values |
| 1104 |
|
| 1105 |
.. attribute:: hash_info.modulus |
| 1106 |
|
| 1107 |
The prime modulus P used for numeric hash scheme |
| 1108 |
|
| 1109 |
.. attribute:: hash_info.inf |
| 1110 |
|
| 1111 |
The hash value returned for a positive infinity |
| 1112 |
|
| 1113 |
.. attribute:: hash_info.nan |
| 1114 |
|
| 1115 |
(This attribute is no longer used) |
| 1116 |
|
| 1117 |
.. attribute:: hash_info.imag |
| 1118 |
|
| 1119 |
The multiplier used for the imaginary part of a complex number |
| 1120 |
|
| 1121 |
.. attribute:: hash_info.algorithm |
| 1122 |
|
| 1123 |
The name of the algorithm for hashing of str, bytes, and memoryview |
| 1124 |
|
| 1125 |
.. attribute:: hash_info.hash_bits |
| 1126 |
|
| 1127 |
The internal output size of the hash algorithm |
| 1128 |
|
| 1129 |
.. attribute:: hash_info.seed_bits |
| 1130 |
|
| 1131 |
The size of the seed key of the hash algorithm |
| 1132 |
|
| 1133 |
.. attribute:: hash_info.cutoff |
| 1134 |
|
| 1135 |
Cutoff for small string DJBX33A optimization in range ``[1, cutoff)``. |
| 1136 |
|
| 1137 |
.. versionadded:: 3.2 |
| 1138 |
|
| 1139 |
.. versionchanged:: 3.4 |
| 1140 |
Added *algorithm*, *hash_bits*, *seed_bits*, and *cutoff*. |
| 1141 |
|
| 1142 |
|
| 1143 |
.. data:: hexversion |
| 1144 |
|
| 1145 |
The version number encoded as a single integer. This is guaranteed to increase |
| 1146 |
with each version, including proper support for non-production releases. For |
| 1147 |
example, to test that the Python interpreter is at least version 1.5.2, use:: |
| 1148 |
|
| 1149 |
if sys.hexversion >= 0x010502F0: |
| 1150 |
# use some advanced feature |
| 1151 |
... |
| 1152 |
else: |
| 1153 |
# use an alternative implementation or warn the user |
| 1154 |
... |
| 1155 |
|
| 1156 |
This is called ``hexversion`` since it only really looks meaningful when viewed |
| 1157 |
as the result of passing it to the built-in :func:`hex` function. The |
| 1158 |
:term:`named tuple` :data:`sys.version_info` may be used for a more |
| 1159 |
human-friendly encoding of the same information. |
| 1160 |
|
| 1161 |
More details of ``hexversion`` can be found at :ref:`apiabiversion`. |
| 1162 |
|
| 1163 |
|
| 1164 |
.. data:: implementation |
| 1165 |
|
| 1166 |
An object containing information about the implementation of the |
| 1167 |
currently running Python interpreter. The following attributes are |
| 1168 |
required to exist in all Python implementations. |
| 1169 |
|
| 1170 |
*name* is the implementation's identifier, e.g. ``'cpython'``. The actual |
| 1171 |
string is defined by the Python implementation, but it is guaranteed to be |
| 1172 |
lower case. |
| 1173 |
|
| 1174 |
*version* is a named tuple, in the same format as |
| 1175 |
:data:`sys.version_info`. It represents the version of the Python |
| 1176 |
*implementation*. This has a distinct meaning from the specific |
| 1177 |
version of the Python *language* to which the currently running |
| 1178 |
interpreter conforms, which ``sys.version_info`` represents. For |
| 1179 |
example, for PyPy 1.8 ``sys.implementation.version`` might be |
| 1180 |
``sys.version_info(1, 8, 0, 'final', 0)``, whereas ``sys.version_info`` |
| 1181 |
would be ``sys.version_info(2, 7, 2, 'final', 0)``. For CPython they |
| 1182 |
are the same value, since it is the reference implementation. |
| 1183 |
|
| 1184 |
*hexversion* is the implementation version in hexadecimal format, like |
| 1185 |
:data:`sys.hexversion`. |
| 1186 |
|
| 1187 |
*cache_tag* is the tag used by the import machinery in the filenames of |
| 1188 |
cached modules. By convention, it would be a composite of the |
| 1189 |
implementation's name and version, like ``'cpython-33'``. However, a |
| 1190 |
Python implementation may use some other value if appropriate. If |
| 1191 |
``cache_tag`` is set to ``None``, it indicates that module caching should |
| 1192 |
be disabled. |
| 1193 |
|
| 1194 |
*supports_isolated_interpreters* is a boolean value, whether |
| 1195 |
this implementation supports multiple isolated interpreters. |
| 1196 |
It is ``True`` for CPython on most platforms. Platforms with |
| 1197 |
this support implement the low-level :mod:`!_interpreters` module. |
| 1198 |
|
| 1199 |
.. seealso:: |
| 1200 |
|
| 1201 |
:pep:`684`, :pep:`734`, and :mod:`concurrent.interpreters`. |
| 1202 |
|
| 1203 |
:data:`sys.implementation` may contain additional attributes specific to |
| 1204 |
the Python implementation. These non-standard attributes must start with |
| 1205 |
an underscore, and are not described here. Regardless of its contents, |
| 1206 |
:data:`sys.implementation` will not change during a run of the interpreter, |
| 1207 |
nor between implementation versions. (It may change between Python |
| 1208 |
language versions, however.) See :pep:`421` for more information. |
| 1209 |
|
| 1210 |
.. versionadded:: 3.3 |
| 1211 |
|
| 1212 |
.. versionchanged:: 3.14 |
| 1213 |
Added ``supports_isolated_interpreters`` field. |
| 1214 |
|
| 1215 |
.. note:: |
| 1216 |
|
| 1217 |
The addition of new required attributes must go through the normal PEP |
| 1218 |
process. See :pep:`421` for more information. |
| 1219 |
|
| 1220 |
.. data:: int_info |
| 1221 |
|
| 1222 |
A :term:`named tuple` that holds information about Python's internal |
| 1223 |
representation of integers. The attributes are read only. |
| 1224 |
|
| 1225 |
.. attribute:: int_info.bits_per_digit |
| 1226 |
|
| 1227 |
The number of bits held in each digit. |
| 1228 |
Python integers are stored internally in base ``2**int_info.bits_per_digit``. |
| 1229 |
|
| 1230 |
.. attribute:: int_info.sizeof_digit |
| 1231 |
|
| 1232 |
The size in bytes of the C type used to represent a digit. |
| 1233 |
|
| 1234 |
.. attribute:: int_info.default_max_str_digits |
| 1235 |
|
| 1236 |
The default value for :func:`sys.get_int_max_str_digits` |
| 1237 |
when it is not otherwise explicitly configured. |
| 1238 |
|
| 1239 |
.. attribute:: int_info.str_digits_check_threshold |
| 1240 |
|
| 1241 |
The minimum non-zero value for :func:`sys.set_int_max_str_digits`, |
| 1242 |
:envvar:`PYTHONINTMAXSTRDIGITS`, or :option:`-X int_max_str_digits <-X>`. |
| 1243 |
|
| 1244 |
.. versionadded:: 3.1 |
| 1245 |
|
| 1246 |
.. versionchanged:: 3.11 |
| 1247 |
|
| 1248 |
Added :attr:`~int_info.default_max_str_digits` and |
| 1249 |
:attr:`~int_info.str_digits_check_threshold`. |
| 1250 |
|
| 1251 |
|
| 1252 |
.. data:: __interactivehook__ |
| 1253 |
|
| 1254 |
When this attribute exists, its value is automatically called (with no |
| 1255 |
arguments) when the interpreter is launched in :ref:`interactive mode |
| 1256 |
<tut-interactive>`. This is done after the :envvar:`PYTHONSTARTUP` file is |
| 1257 |
read, so that you can set this hook there. The :mod:`site` module |
| 1258 |
:ref:`sets this <rlcompleter-config>`. |
| 1259 |
|
| 1260 |
.. audit-event:: cpython.run_interactivehook hook sys.__interactivehook__ |
| 1261 |
|
| 1262 |
Raises an :ref:`auditing event <auditing>` |
| 1263 |
``cpython.run_interactivehook`` with the hook object as the argument when |
| 1264 |
the hook is called on startup. |
| 1265 |
|
| 1266 |
.. versionadded:: 3.4 |
| 1267 |
|
| 1268 |
|
| 1269 |
.. function:: intern(string) |
| 1270 |
|
| 1271 |
Enter *string* in the table of "interned" strings and return the interned string |
| 1272 |
-- which is *string* itself or a copy. Interning strings is useful to gain a |
| 1273 |
little performance on dictionary lookup -- if the keys in a dictionary are |
| 1274 |
interned, and the lookup key is interned, the key comparisons (after hashing) |
| 1275 |
can be done by a pointer compare instead of a string compare. Normally, the |
| 1276 |
names used in Python programs are automatically interned, and the dictionaries |
| 1277 |
used to hold module, class or instance attributes have interned keys. |
| 1278 |
|
| 1279 |
Interned strings are not :term:`immortal`; you must keep a reference to the |
| 1280 |
return value of :func:`intern` around to benefit from it. |
| 1281 |
|
| 1282 |
|
| 1283 |
.. function:: _is_gil_enabled() |
| 1284 |
|
| 1285 |
Return :const:`True` if the :term:`GIL` is enabled and :const:`False` if |
| 1286 |
it is disabled. |
| 1287 |
|
| 1288 |
.. versionadded:: 3.13 |
| 1289 |
|
| 1290 |
.. impl-detail:: |
| 1291 |
|
| 1292 |
It is not guaranteed to exist in all implementations of Python. |
| 1293 |
|
| 1294 |
.. function:: is_finalizing() |
| 1295 |
|
| 1296 |
Return :const:`True` if the main Python interpreter is |
| 1297 |
:term:`shutting down <interpreter shutdown>`. Return :const:`False` otherwise. |
| 1298 |
|
| 1299 |
See also the :exc:`PythonFinalizationError` exception. |
| 1300 |
|
| 1301 |
.. versionadded:: 3.5 |
| 1302 |
|
| 1303 |
.. data:: _jit |
| 1304 |
|
| 1305 |
Utilities for observing just-in-time compilation. |
| 1306 |
|
| 1307 |
.. impl-detail:: |
| 1308 |
|
| 1309 |
JIT compilation is an *experimental implementation detail* of CPython. |
| 1310 |
``sys._jit`` is not guaranteed to exist or behave the same way in all |
| 1311 |
Python implementations, versions, or build configurations. |
| 1312 |
|
| 1313 |
.. versionadded:: 3.14 |
| 1314 |
|
| 1315 |
.. function:: _jit.is_available() |
| 1316 |
|
| 1317 |
Return ``True`` if the current Python executable supports JIT compilation, |
| 1318 |
and ``False`` otherwise. This can be controlled by building CPython with |
| 1319 |
the ``--experimental-jit`` option on Windows, and the |
| 1320 |
:option:`--enable-experimental-jit` option on all other platforms. |
| 1321 |
|
| 1322 |
.. function:: _jit.is_enabled() |
| 1323 |
|
| 1324 |
Return ``True`` if JIT compilation is enabled for the current Python |
| 1325 |
process (implies :func:`sys._jit.is_available`), and ``False`` otherwise. |
| 1326 |
If JIT compilation is available, this can be controlled by setting the |
| 1327 |
:envvar:`PYTHON_JIT` environment variable to ``0`` (disabled) or ``1`` |
| 1328 |
(enabled) at interpreter startup. |
| 1329 |
|
| 1330 |
.. function:: _jit.is_active() |
| 1331 |
|
| 1332 |
Return ``True`` if the topmost Python frame is currently executing JIT |
| 1333 |
code (implies :func:`sys._jit.is_enabled`), and ``False`` otherwise. |
| 1334 |
|
| 1335 |
.. note:: |
| 1336 |
|
| 1337 |
This function is intended for testing and debugging the JIT itself. |
| 1338 |
It should be avoided for any other purpose. |
| 1339 |
|
| 1340 |
.. note:: |
| 1341 |
|
| 1342 |
Due to the nature of tracing JIT compilers, repeated calls to this |
| 1343 |
function may give surprising results. For example, branching on its |
| 1344 |
return value will likely lead to unexpected behavior (if doing so |
| 1345 |
causes JIT code to be entered or exited): |
| 1346 |
|
| 1347 |
.. code-block:: pycon |
| 1348 |
|
| 1349 |
>>> for warmup in range(BIG_NUMBER): |
| 1350 |
... # This line is "hot", and is eventually JIT-compiled: |
| 1351 |
... if sys._jit.is_active(): |
| 1352 |
... # This line is "cold", and is run in the interpreter: |
| 1353 |
... assert sys._jit.is_active() |
| 1354 |
... |
| 1355 |
Traceback (most recent call last): |
| 1356 |
File "<stdin>", line 5, in <module> |
| 1357 |
assert sys._jit.is_active() |
| 1358 |
~~~~~~~~~~~~~~~~~~^^ |
| 1359 |
AssertionError |
| 1360 |
|
| 1361 |
.. data:: last_exc |
| 1362 |
|
| 1363 |
This variable is not always defined; it is set to the exception instance |
| 1364 |
when an exception is not handled and the interpreter prints an error message |
| 1365 |
and a stack traceback. Its intended use is to allow an interactive user to |
| 1366 |
import a debugger module and engage in post-mortem debugging without having |
| 1367 |
to re-execute the command that caused the error. (Typical use is |
| 1368 |
``import pdb; pdb.pm()`` to enter the post-mortem debugger; see :mod:`pdb` |
| 1369 |
module for more information.) |
| 1370 |
|
| 1371 |
.. versionadded:: 3.12 |
| 1372 |
|
| 1373 |
.. function:: _is_immortal(op) |
| 1374 |
|
| 1375 |
Return :const:`True` if the given object is :term:`immortal`, :const:`False` |
| 1376 |
otherwise. |
| 1377 |
|
| 1378 |
.. note:: |
| 1379 |
|
| 1380 |
Objects that are immortal (and thus return ``True`` upon being passed |
| 1381 |
to this function) are not guaranteed to be immortal in future versions, |
| 1382 |
and vice versa for mortal objects. |
| 1383 |
|
| 1384 |
.. versionadded:: 3.14 |
| 1385 |
|
| 1386 |
.. impl-detail:: |
| 1387 |
|
| 1388 |
This function should be used for specialized purposes only. |
| 1389 |
It is not guaranteed to exist in all implementations of Python. |
| 1390 |
|
| 1391 |
.. function:: _is_interned(string) |
| 1392 |
|
| 1393 |
Return :const:`True` if the given string is "interned", :const:`False` |
| 1394 |
otherwise. |
| 1395 |
|
| 1396 |
.. versionadded:: 3.13 |
| 1397 |
|
| 1398 |
.. impl-detail:: |
| 1399 |
|
| 1400 |
It is not guaranteed to exist in all implementations of Python. |
| 1401 |
|
| 1402 |
|
| 1403 |
.. data:: last_type |
| 1404 |
last_value |
| 1405 |
last_traceback |
| 1406 |
|
| 1407 |
These three variables are deprecated; use :data:`sys.last_exc` instead. |
| 1408 |
They hold the legacy representation of ``sys.last_exc``, as returned |
| 1409 |
from :func:`exc_info` above. |
| 1410 |
|
| 1411 |
.. data:: maxsize |
| 1412 |
|
| 1413 |
An integer giving the maximum value a variable of type :c:type:`Py_ssize_t` can |
| 1414 |
take. It's usually ``2**31 - 1`` on a 32-bit platform and ``2**63 - 1`` on a |
| 1415 |
64-bit platform. |
| 1416 |
|
| 1417 |
|
| 1418 |
.. data:: maxunicode |
| 1419 |
|
| 1420 |
An integer giving the value of the largest Unicode code point, |
| 1421 |
i.e. ``1114111`` (``0x10FFFF`` in hexadecimal). |
| 1422 |
|
| 1423 |
.. versionchanged:: 3.3 |
| 1424 |
Before :pep:`393`, ``sys.maxunicode`` used to be either ``0xFFFF`` |
| 1425 |
or ``0x10FFFF``, depending on the configuration option that specified |
| 1426 |
whether Unicode characters were stored as UCS-2 or UCS-4. |
| 1427 |
|
| 1428 |
|
| 1429 |
.. data:: meta_path |
| 1430 |
|
| 1431 |
A list of :term:`meta path finder` objects that have their |
| 1432 |
:meth:`~importlib.abc.MetaPathFinder.find_spec` methods called to see if one |
| 1433 |
of the objects can find the module to be imported. By default, it holds entries |
| 1434 |
that implement Python's default import semantics. The |
| 1435 |
:meth:`~importlib.abc.MetaPathFinder.find_spec` method is called with at |
| 1436 |
least the absolute name of the module being imported. If the module to be |
| 1437 |
imported is contained in a package, then the parent package's |
| 1438 |
:attr:`~module.__path__` |
| 1439 |
attribute is passed in as a second argument. The method returns a |
| 1440 |
:term:`module spec`, or ``None`` if the module cannot be found. |
| 1441 |
|
| 1442 |
.. seealso:: |
| 1443 |
|
| 1444 |
:class:`importlib.abc.MetaPathFinder` |
| 1445 |
The abstract base class defining the interface of finder objects on |
| 1446 |
:data:`meta_path`. |
| 1447 |
:class:`importlib.machinery.ModuleSpec` |
| 1448 |
The concrete class which |
| 1449 |
:meth:`~importlib.abc.MetaPathFinder.find_spec` should return |
| 1450 |
instances of. |
| 1451 |
|
| 1452 |
.. versionchanged:: 3.4 |
| 1453 |
|
| 1454 |
:term:`Module specs <module spec>` were introduced in Python 3.4, by |
| 1455 |
:pep:`451`. |
| 1456 |
|
| 1457 |
.. versionchanged:: 3.12 |
| 1458 |
|
| 1459 |
Removed the fallback that looked for a :meth:`!find_module` method |
| 1460 |
if a :data:`meta_path` entry didn't have a |
| 1461 |
:meth:`~importlib.abc.MetaPathFinder.find_spec` method. |
| 1462 |
|
| 1463 |
.. data:: modules |
| 1464 |
|
| 1465 |
This is a dictionary that maps module names to modules which have already been |
| 1466 |
loaded. This can be manipulated to force reloading of modules and other tricks. |
| 1467 |
However, replacing the dictionary will not necessarily work as expected and |
| 1468 |
deleting essential items from the dictionary may cause Python to fail. If |
| 1469 |
you want to iterate over this global dictionary always use |
| 1470 |
``sys.modules.copy()`` or ``tuple(sys.modules)`` to avoid exceptions as its |
| 1471 |
size may change during iteration as a side effect of code or activity in |
| 1472 |
other threads. |
| 1473 |
|
| 1474 |
|
| 1475 |
.. data:: orig_argv |
| 1476 |
|
| 1477 |
The list of the original command line arguments passed to the Python |
| 1478 |
executable. |
| 1479 |
|
| 1480 |
The elements of :data:`sys.orig_argv` are the arguments to the Python interpreter, |
| 1481 |
while the elements of :data:`sys.argv` are the arguments to the user's program. |
| 1482 |
Arguments consumed by the interpreter itself will be present in :data:`sys.orig_argv` |
| 1483 |
and missing from :data:`sys.argv`. |
| 1484 |
|
| 1485 |
.. versionadded:: 3.10 |
| 1486 |
|
| 1487 |
|
| 1488 |
.. data:: path |
| 1489 |
|
| 1490 |
.. index:: triple: module; search; path |
| 1491 |
|
| 1492 |
A list of strings that specifies the search path for modules. Initialized from |
| 1493 |
the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent |
| 1494 |
default. |
| 1495 |
|
| 1496 |
By default, as initialized upon program startup, a potentially unsafe path |
| 1497 |
is prepended to :data:`sys.path` (*before* the entries inserted as a result |
| 1498 |
of :envvar:`PYTHONPATH`): |
| 1499 |
|
| 1500 |
* ``python -m module`` command line: prepend the current working |
| 1501 |
directory. |
| 1502 |
* ``python script.py`` command line: prepend the script's directory. |
| 1503 |
If it's a symbolic link, resolve symbolic links. |
| 1504 |
* ``python -c code`` and ``python`` (REPL) command lines: prepend an empty |
| 1505 |
string, which means the current working directory. |
| 1506 |
|
| 1507 |
To not prepend this potentially unsafe path, use the :option:`-P` command |
| 1508 |
line option or the :envvar:`PYTHONSAFEPATH` environment variable. |
| 1509 |
|
| 1510 |
A program is free to modify this list for its own purposes. Only strings |
| 1511 |
should be added to :data:`sys.path`; all other data types are |
| 1512 |
ignored during import. |
| 1513 |
|
| 1514 |
|
| 1515 |
.. seealso:: |
| 1516 |
* Module :mod:`site` This describes how to use .pth files to |
| 1517 |
extend :data:`sys.path`. |
| 1518 |
|
| 1519 |
.. data:: path_hooks |
| 1520 |
|
| 1521 |
A list of callables that take a path argument to try to create a |
| 1522 |
:term:`finder` for the path. If a finder can be created, it is to be |
| 1523 |
returned by the callable, else raise :exc:`ImportError`. |
| 1524 |
|
| 1525 |
Originally specified in :pep:`302`. |
| 1526 |
|
| 1527 |
|
| 1528 |
.. data:: path_importer_cache |
| 1529 |
|
| 1530 |
A dictionary acting as a cache for :term:`finder` objects. The keys are |
| 1531 |
paths that have been passed to :data:`sys.path_hooks` and the values are |
| 1532 |
the finders that are found. If a path is a valid file system path but no |
| 1533 |
finder is found on :data:`sys.path_hooks` then ``None`` is |
| 1534 |
stored. |
| 1535 |
|
| 1536 |
Originally specified in :pep:`302`. |
| 1537 |
|
| 1538 |
|
| 1539 |
.. data:: platform |
| 1540 |
|
| 1541 |
A string containing a platform identifier. Known values are: |
| 1542 |
|
| 1543 |
================ =========================== |
| 1544 |
System ``platform`` value |
| 1545 |
================ =========================== |
| 1546 |
AIX ``'aix'`` |
| 1547 |
Android ``'android'`` |
| 1548 |
Emscripten ``'emscripten'`` |
| 1549 |
FreeBSD ``'freebsd'`` |
| 1550 |
iOS ``'ios'`` |
| 1551 |
Linux ``'linux'`` |
| 1552 |
macOS ``'darwin'`` |
| 1553 |
Windows ``'win32'`` |
| 1554 |
Windows/Cygwin ``'cygwin'`` |
| 1555 |
WASI ``'wasi'`` |
| 1556 |
================ =========================== |
| 1557 |
|
| 1558 |
On Unix systems not listed in the table, the value is the lowercased OS name |
| 1559 |
as returned by ``uname -s``, with the first part of the version as returned by |
| 1560 |
``uname -r`` appended, e.g. ``'sunos5'``, *at the time when Python was built*. |
| 1561 |
Unless you want to test for a specific system version, it is therefore |
| 1562 |
recommended to use the following idiom:: |
| 1563 |
|
| 1564 |
if sys.platform.startswith('sunos'): |
| 1565 |
# SunOS-specific code here... |
| 1566 |
|
| 1567 |
.. versionchanged:: 3.3 |
| 1568 |
On Linux, :data:`sys.platform` doesn't contain the major version anymore. |
| 1569 |
It is always ``'linux'``, instead of ``'linux2'`` or ``'linux3'``. |
| 1570 |
|
| 1571 |
.. versionchanged:: 3.8 |
| 1572 |
On AIX, :data:`sys.platform` doesn't contain the major version anymore. |
| 1573 |
It is always ``'aix'``, instead of ``'aix5'`` or ``'aix7'``. |
| 1574 |
|
| 1575 |
.. versionchanged:: 3.13 |
| 1576 |
On Android, :data:`sys.platform` now returns ``'android'`` rather than |
| 1577 |
``'linux'``. |
| 1578 |
|
| 1579 |
.. versionchanged:: 3.14 |
| 1580 |
On FreeBSD, :data:`sys.platform` doesn't contain the major version anymore. |
| 1581 |
It is always ``'freebsd'``, instead of ``'freebsd13'`` or ``'freebsd14'``. |
| 1582 |
|
| 1583 |
.. seealso:: |
| 1584 |
|
| 1585 |
:data:`os.name` has a coarser granularity. :func:`os.uname` gives |
| 1586 |
system-dependent version information. |
| 1587 |
|
| 1588 |
The :mod:`platform` module provides detailed checks for the |
| 1589 |
system's identity. |
| 1590 |
|
| 1591 |
|
| 1592 |
.. data:: platlibdir |
| 1593 |
|
| 1594 |
Name of the platform-specific library directory. It is used to build the |
| 1595 |
path of standard library and the paths of installed extension modules. |
| 1596 |
|
| 1597 |
It is equal to ``"lib"`` on most platforms. On Fedora and SuSE, it is equal |
| 1598 |
to ``"lib64"`` on 64-bit platforms which gives the following ``sys.path`` |
| 1599 |
paths (where ``X.Y`` is the Python ``major.minor`` version): |
| 1600 |
|
| 1601 |
* ``/usr/lib64/pythonX.Y/``: |
| 1602 |
Standard library (like ``os.py`` of the :mod:`os` module) |
| 1603 |
* ``/usr/lib64/pythonX.Y/lib-dynload/``: |
| 1604 |
C extension modules of the standard library (like the :mod:`errno` module, |
| 1605 |
the exact filename is platform specific) |
| 1606 |
* ``/usr/lib/pythonX.Y/site-packages/`` (always use ``lib``, not |
| 1607 |
:data:`sys.platlibdir`): Third-party modules |
| 1608 |
* ``/usr/lib64/pythonX.Y/site-packages/``: |
| 1609 |
C extension modules of third-party packages |
| 1610 |
|
| 1611 |
.. versionadded:: 3.9 |
| 1612 |
|
| 1613 |
|
| 1614 |
.. data:: prefix |
| 1615 |
|
| 1616 |
A string giving the site-specific directory prefix where the platform |
| 1617 |
independent Python files are installed; on Unix, the default is |
| 1618 |
:file:`/usr/local`. This can be set at build time with the :option:`--prefix` |
| 1619 |
argument to the :program:`configure` script. See |
| 1620 |
:ref:`installation_paths` for derived paths. |
| 1621 |
|
| 1622 |
.. note:: |
| 1623 |
|
| 1624 |
If a :ref:`virtual environment <venv-def>` is in effect, this :data:`prefix` |
| 1625 |
will point to the virtual environment. The value for the Python installation |
| 1626 |
will still be available, via :data:`base_prefix`. |
| 1627 |
Refer to :ref:`sys-path-init-virtual-environments` for more information. |
| 1628 |
|
| 1629 |
.. versionchanged:: 3.14 |
| 1630 |
|
| 1631 |
When running under a :ref:`virtual environment <venv-def>`, |
| 1632 |
:data:`prefix` and :data:`exec_prefix` are now set to the virtual |
| 1633 |
environment prefix by the :ref:`path initialization <sys-path-init>`, |
| 1634 |
instead of :mod:`site`. This means that :data:`prefix` and |
| 1635 |
:data:`exec_prefix` always point to the virtual environment, even when |
| 1636 |
:mod:`site` is disabled (:option:`-S`). |
| 1637 |
|
| 1638 |
|
| 1639 |
.. data:: ps1 |
| 1640 |
ps2 |
| 1641 |
|
| 1642 |
.. index:: |
| 1643 |
single: interpreter prompts |
| 1644 |
single: prompts, interpreter |
| 1645 |
single: >>>; interpreter prompt |
| 1646 |
single: ...; interpreter prompt |
| 1647 |
|
| 1648 |
Strings specifying the primary and secondary prompt of the interpreter. These |
| 1649 |
are only defined if the interpreter is in interactive mode. Their initial |
| 1650 |
values in this case are ``'>>> '`` and ``'... '``. If a non-string object is |
| 1651 |
assigned to either variable, its :func:`str` is re-evaluated each time the |
| 1652 |
interpreter prepares to read a new interactive command; this can be used to |
| 1653 |
implement a dynamic prompt. |
| 1654 |
|
| 1655 |
|
| 1656 |
.. function:: setdlopenflags(n) |
| 1657 |
|
| 1658 |
Set the flags used by the interpreter for :c:func:`dlopen` calls, such as when |
| 1659 |
the interpreter loads extension modules. Among other things, this will enable a |
| 1660 |
lazy resolving of symbols when importing a module, if called as |
| 1661 |
``sys.setdlopenflags(0)``. To share symbols across extension modules, call as |
| 1662 |
``sys.setdlopenflags(os.RTLD_GLOBAL)``. Symbolic names for the flag values |
| 1663 |
can be found in the :mod:`os` module (:samp:`RTLD_{xxx}` constants, e.g. |
| 1664 |
:const:`os.RTLD_LAZY`). |
| 1665 |
|
| 1666 |
.. availability:: Unix. |
| 1667 |
|
| 1668 |
.. function:: set_int_max_str_digits(maxdigits) |
| 1669 |
|
| 1670 |
Set the :ref:`integer string conversion length limitation |
| 1671 |
<int_max_str_digits>` used by this interpreter. See also |
| 1672 |
:func:`get_int_max_str_digits`. |
| 1673 |
|
| 1674 |
.. versionadded:: 3.11 |
| 1675 |
|
| 1676 |
.. function:: setprofile(profilefunc) |
| 1677 |
|
| 1678 |
.. index:: |
| 1679 |
single: profile function |
| 1680 |
single: profiler |
| 1681 |
|
| 1682 |
Set the system's profile function, which allows you to implement a Python source |
| 1683 |
code profiler in Python. See chapter :ref:`profile` for more information on the |
| 1684 |
Python profiler. The system's profile function is called similarly to the |
| 1685 |
system's trace function (see :func:`settrace`), but it is called with different events, |
| 1686 |
for example it isn't called for each executed line of code (only on call and return, |
| 1687 |
but the return event is reported even when an exception has been set). The function is |
| 1688 |
thread-specific, but there is no way for the profiler to know about context switches between |
| 1689 |
threads, so it does not make sense to use this in the presence of multiple threads. Also, |
| 1690 |
its return value is not used, so it can simply return ``None``. Error in the profile |
| 1691 |
function will cause itself unset. |
| 1692 |
|
| 1693 |
.. note:: |
| 1694 |
The same tracing mechanism is used for :func:`!setprofile` as :func:`settrace`. |
| 1695 |
To trace calls with :func:`!setprofile` inside a tracing function |
| 1696 |
(e.g. in a debugger breakpoint), see :func:`call_tracing`. |
| 1697 |
|
| 1698 |
Profile functions should have three arguments: *frame*, *event*, and |
| 1699 |
*arg*. *frame* is the current stack frame. *event* is a string: ``'call'``, |
| 1700 |
``'return'``, ``'c_call'``, ``'c_return'``, or ``'c_exception'``. *arg* depends |
| 1701 |
on the event type. |
| 1702 |
|
| 1703 |
The events have the following meaning: |
| 1704 |
|
| 1705 |
``'call'`` |
| 1706 |
A function is called (or some other code block entered). The |
| 1707 |
profile function is called; *arg* is ``None``. |
| 1708 |
|
| 1709 |
``'return'`` |
| 1710 |
A function (or other code block) is about to return. The profile |
| 1711 |
function is called; *arg* is the value that will be returned, or ``None`` |
| 1712 |
if the event is caused by an exception being raised. |
| 1713 |
|
| 1714 |
``'c_call'`` |
| 1715 |
A C function is about to be called. This may be an extension function or |
| 1716 |
a built-in. *arg* is the C function object. |
| 1717 |
|
| 1718 |
``'c_return'`` |
| 1719 |
A C function has returned. *arg* is the C function object. |
| 1720 |
|
| 1721 |
``'c_exception'`` |
| 1722 |
A C function has raised an exception. *arg* is the C function object. |
| 1723 |
|
| 1724 |
.. audit-event:: sys.setprofile "" sys.setprofile |
| 1725 |
|
| 1726 |
|
| 1727 |
.. function:: setrecursionlimit(limit) |
| 1728 |
|
| 1729 |
Set the maximum depth of the Python interpreter stack to *limit*. This limit |
| 1730 |
prevents infinite recursion from causing an overflow of the C stack and crashing |
| 1731 |
Python. |
| 1732 |
|
| 1733 |
The highest possible limit is platform-dependent. A user may need to set the |
| 1734 |
limit higher when they have a program that requires deep recursion and a platform |
| 1735 |
that supports a higher limit. This should be done with care, because a too-high |
| 1736 |
limit can lead to a crash. |
| 1737 |
|
| 1738 |
If the new limit is too low at the current recursion depth, a |
| 1739 |
:exc:`RecursionError` exception is raised. |
| 1740 |
|
| 1741 |
.. versionchanged:: 3.5.1 |
| 1742 |
A :exc:`RecursionError` exception is now raised if the new limit is too |
| 1743 |
low at the current recursion depth. |
| 1744 |
|
| 1745 |
|
| 1746 |
.. function:: setswitchinterval(interval) |
| 1747 |
|
| 1748 |
Set the interpreter's thread switch interval (in seconds). This floating-point |
| 1749 |
value determines the ideal duration of the "timeslices" allocated to |
| 1750 |
concurrently running Python threads. Please note that the actual value |
| 1751 |
can be higher, especially if long-running internal functions or methods |
| 1752 |
are used. Also, which thread becomes scheduled at the end of the interval |
| 1753 |
is the operating system's decision. The interpreter doesn't have its |
| 1754 |
own scheduler. |
| 1755 |
|
| 1756 |
.. versionadded:: 3.2 |
| 1757 |
|
| 1758 |
|
| 1759 |
.. function:: settrace(tracefunc) |
| 1760 |
|
| 1761 |
.. index:: |
| 1762 |
single: trace function |
| 1763 |
single: debugger |
| 1764 |
|
| 1765 |
Set the system's trace function, which allows you to implement a Python |
| 1766 |
source code debugger in Python. The function is thread-specific; for a |
| 1767 |
debugger to support multiple threads, it must register a trace function using |
| 1768 |
:func:`settrace` for each thread being debugged or use :func:`threading.settrace`. |
| 1769 |
|
| 1770 |
Trace functions should have three arguments: *frame*, *event*, and |
| 1771 |
*arg*. *frame* is the :ref:`current stack frame <frame-objects>`. *event* is a string: ``'call'``, |
| 1772 |
``'line'``, ``'return'``, ``'exception'`` or ``'opcode'``. *arg* depends on |
| 1773 |
the event type. |
| 1774 |
|
| 1775 |
The trace function is invoked (with *event* set to ``'call'``) whenever a new |
| 1776 |
local scope is entered; it should return a reference to a local trace |
| 1777 |
function to be used for the new scope, or ``None`` if the scope shouldn't be |
| 1778 |
traced. |
| 1779 |
|
| 1780 |
The local trace function should return a reference to itself, or to another |
| 1781 |
function which would then be used as the local trace function for the scope. |
| 1782 |
|
| 1783 |
If there is any error occurred in the trace function, it will be unset, just |
| 1784 |
like ``settrace(None)`` is called. |
| 1785 |
|
| 1786 |
.. note:: |
| 1787 |
Tracing is disabled while calling the trace function (e.g. a function set by |
| 1788 |
:func:`!settrace`). For recursive tracing see :func:`call_tracing`. |
| 1789 |
|
| 1790 |
The events have the following meaning: |
| 1791 |
|
| 1792 |
``'call'`` |
| 1793 |
A function is called (or some other code block entered). The |
| 1794 |
global trace function is called; *arg* is ``None``; the return value |
| 1795 |
specifies the local trace function. |
| 1796 |
|
| 1797 |
``'line'`` |
| 1798 |
The interpreter is about to execute a new line of code or re-execute the |
| 1799 |
condition of a loop. The local trace function is called; *arg* is |
| 1800 |
``None``; the return value specifies the new local trace function. See |
| 1801 |
:file:`Objects/lnotab_notes.txt` for a detailed explanation of how this |
| 1802 |
works. |
| 1803 |
Per-line events may be disabled for a frame by setting |
| 1804 |
:attr:`~frame.f_trace_lines` to :const:`False` on that |
| 1805 |
:ref:`frame <frame-objects>`. |
| 1806 |
|
| 1807 |
``'return'`` |
| 1808 |
A function (or other code block) is about to return. The local trace |
| 1809 |
function is called; *arg* is the value that will be returned, or ``None`` |
| 1810 |
if the event is caused by an exception being raised. The trace function's |
| 1811 |
return value is ignored. |
| 1812 |
|
| 1813 |
``'exception'`` |
| 1814 |
An exception has occurred. The local trace function is called; *arg* is a |
| 1815 |
tuple ``(exception, value, traceback)``; the return value specifies the |
| 1816 |
new local trace function. |
| 1817 |
|
| 1818 |
``'opcode'`` |
| 1819 |
The interpreter is about to execute a new opcode (see :mod:`dis` for |
| 1820 |
opcode details). The local trace function is called; *arg* is |
| 1821 |
``None``; the return value specifies the new local trace function. |
| 1822 |
Per-opcode events are not emitted by default: they must be explicitly |
| 1823 |
requested by setting :attr:`~frame.f_trace_opcodes` to :const:`True` on the |
| 1824 |
:ref:`frame <frame-objects>`. |
| 1825 |
|
| 1826 |
Note that as an exception is propagated down the chain of callers, an |
| 1827 |
``'exception'`` event is generated at each level. |
| 1828 |
|
| 1829 |
For more fine-grained usage, it's possible to set a trace function by |
| 1830 |
assigning ``frame.f_trace = tracefunc`` explicitly, rather than relying on |
| 1831 |
it being set indirectly via the return value from an already installed |
| 1832 |
trace function. This is also required for activating the trace function on |
| 1833 |
the current frame, which :func:`settrace` doesn't do. Note that in order |
| 1834 |
for this to work, a global tracing function must have been installed |
| 1835 |
with :func:`settrace` in order to enable the runtime tracing machinery, |
| 1836 |
but it doesn't need to be the same tracing function (e.g. it could be a |
| 1837 |
low overhead tracing function that simply returns ``None`` to disable |
| 1838 |
itself immediately on each frame). |
| 1839 |
|
| 1840 |
For more information on code and frame objects, refer to :ref:`types`. |
| 1841 |
|
| 1842 |
.. audit-event:: sys.settrace "" sys.settrace |
| 1843 |
|
| 1844 |
.. impl-detail:: |
| 1845 |
|
| 1846 |
The :func:`settrace` function is intended only for implementing debuggers, |
| 1847 |
profilers, coverage tools and the like. Its behavior is part of the |
| 1848 |
implementation platform, rather than part of the language definition, and |
| 1849 |
thus may not be available in all Python implementations. |
| 1850 |
|
| 1851 |
.. versionchanged:: 3.7 |
| 1852 |
|
| 1853 |
``'opcode'`` event type added; :attr:`~frame.f_trace_lines` and |
| 1854 |
:attr:`~frame.f_trace_opcodes` attributes added to frames |
| 1855 |
|
| 1856 |
.. function:: set_asyncgen_hooks([firstiter] [, finalizer]) |
| 1857 |
|
| 1858 |
Accepts two optional keyword arguments which are callables that accept an |
| 1859 |
:term:`asynchronous generator iterator` as an argument. The *firstiter* |
| 1860 |
callable will be called when an asynchronous generator is iterated for the |
| 1861 |
first time. The *finalizer* will be called when an asynchronous generator |
| 1862 |
is about to be garbage collected. |
| 1863 |
|
| 1864 |
.. audit-event:: sys.set_asyncgen_hooks_firstiter "" sys.set_asyncgen_hooks |
| 1865 |
|
| 1866 |
.. audit-event:: sys.set_asyncgen_hooks_finalizer "" sys.set_asyncgen_hooks |
| 1867 |
|
| 1868 |
Two auditing events are raised because the underlying API consists of two |
| 1869 |
calls, each of which must raise its own event. |
| 1870 |
|
| 1871 |
.. versionadded:: 3.6 |
| 1872 |
See :pep:`525` for more details, and for a reference example of a |
| 1873 |
*finalizer* method see the implementation of |
| 1874 |
``asyncio.Loop.shutdown_asyncgens`` in |
| 1875 |
:source:`Lib/asyncio/base_events.py` |
| 1876 |
|
| 1877 |
.. note:: |
| 1878 |
This function has been added on a provisional basis (see :pep:`411` |
| 1879 |
for details.) |
| 1880 |
|
| 1881 |
.. function:: set_coroutine_origin_tracking_depth(depth) |
| 1882 |
|
| 1883 |
Allows enabling or disabling coroutine origin tracking. When |
| 1884 |
enabled, the ``cr_origin`` attribute on coroutine objects will |
| 1885 |
contain a tuple of (filename, line number, function name) tuples |
| 1886 |
describing the traceback where the coroutine object was created, |
| 1887 |
with the most recent call first. When disabled, ``cr_origin`` will |
| 1888 |
be ``None``. |
| 1889 |
|
| 1890 |
To enable, pass a *depth* value greater than zero; this sets the |
| 1891 |
number of frames whose information will be captured. To disable, |
| 1892 |
set *depth* to zero. |
| 1893 |
|
| 1894 |
This setting is thread-specific. |
| 1895 |
|
| 1896 |
.. versionadded:: 3.7 |
| 1897 |
|
| 1898 |
.. note:: |
| 1899 |
This function has been added on a provisional basis (see :pep:`411` |
| 1900 |
for details.) Use it only for debugging purposes. |
| 1901 |
|
| 1902 |
.. function:: activate_stack_trampoline(backend, /) |
| 1903 |
|
| 1904 |
Activate the stack profiler trampoline *backend*. |
| 1905 |
The only supported backend is ``"perf"``. |
| 1906 |
|
| 1907 |
Stack trampolines cannot be activated if the JIT is active. |
| 1908 |
|
| 1909 |
.. availability:: Linux. |
| 1910 |
|
| 1911 |
.. versionadded:: 3.12 |
| 1912 |
|
| 1913 |
.. seealso:: |
| 1914 |
|
| 1915 |
* :ref:`perf_profiling` |
| 1916 |
* https://perf.wiki.kernel.org |
| 1917 |
|
| 1918 |
.. function:: deactivate_stack_trampoline() |
| 1919 |
|
| 1920 |
Deactivate the current stack profiler trampoline backend. |
| 1921 |
|
| 1922 |
If no stack profiler is activated, this function has no effect. |
| 1923 |
|
| 1924 |
.. availability:: Linux. |
| 1925 |
|
| 1926 |
.. versionadded:: 3.12 |
| 1927 |
|
| 1928 |
.. function:: is_stack_trampoline_active() |
| 1929 |
|
| 1930 |
Return ``True`` if a stack profiler trampoline is active. |
| 1931 |
|
| 1932 |
.. availability:: Linux. |
| 1933 |
|
| 1934 |
.. versionadded:: 3.12 |
| 1935 |
|
| 1936 |
|
| 1937 |
.. function:: remote_exec(pid, script) |
| 1938 |
|
| 1939 |
Executes *script*, a file containing Python code in the remote |
| 1940 |
process with the given *pid*. |
| 1941 |
|
| 1942 |
This function returns immediately, and the code will be executed by the |
| 1943 |
target process's main thread at the next available opportunity, similarly |
| 1944 |
to how signals are handled. There is no interface to determine when the |
| 1945 |
code has been executed. The caller is responsible for making sure that |
| 1946 |
the file still exists whenever the remote process tries to read it and that |
| 1947 |
it hasn't been overwritten. |
| 1948 |
|
| 1949 |
The remote process must be running a CPython interpreter of the same major |
| 1950 |
and minor version as the local process. If either the local or remote |
| 1951 |
interpreter is pre-release (alpha, beta, or release candidate) then the |
| 1952 |
local and remote interpreters must be the same exact version. |
| 1953 |
|
| 1954 |
See :ref:`remote-debugging` for more information about the remote debugging |
| 1955 |
mechanism. |
| 1956 |
|
| 1957 |
.. audit-event:: sys.remote_exec pid script_path |
| 1958 |
|
| 1959 |
When the code is executed in the remote process, an |
| 1960 |
:ref:`auditing event <auditing>` ``sys.remote_exec`` is raised with |
| 1961 |
the *pid* and the path to the script file. |
| 1962 |
This event is raised in the process that called :func:`sys.remote_exec`. |
| 1963 |
|
| 1964 |
.. audit-event:: cpython.remote_debugger_script script_path |
| 1965 |
|
| 1966 |
When the script is executed in the remote process, an |
| 1967 |
:ref:`auditing event <auditing>` |
| 1968 |
``cpython.remote_debugger_script`` is raised |
| 1969 |
with the path in the remote process. |
| 1970 |
This event is raised in the remote process, not the one |
| 1971 |
that called :func:`sys.remote_exec`. |
| 1972 |
|
| 1973 |
.. availability:: Unix, Windows. |
| 1974 |
.. versionadded:: 3.14 |
| 1975 |
See :pep:`768` for more details. |
| 1976 |
|
| 1977 |
|
| 1978 |
.. function:: _enablelegacywindowsfsencoding() |
| 1979 |
|
| 1980 |
Changes the :term:`filesystem encoding and error handler` to 'mbcs' and |
| 1981 |
'replace' respectively, for consistency with versions of Python prior to |
| 1982 |
3.6. |
| 1983 |
|
| 1984 |
This is equivalent to defining the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` |
| 1985 |
environment variable before launching Python. |
| 1986 |
|
| 1987 |
See also :func:`sys.getfilesystemencoding` and |
| 1988 |
:func:`sys.getfilesystemencodeerrors`. |
| 1989 |
|
| 1990 |
.. availability:: Windows. |
| 1991 |
|
| 1992 |
.. note:: |
| 1993 |
Changing the filesystem encoding after Python startup is risky because |
| 1994 |
the old fsencoding or paths encoded by the old fsencoding may be cached |
| 1995 |
somewhere. Use :envvar:`PYTHONLEGACYWINDOWSFSENCODING` instead. |
| 1996 |
|
| 1997 |
.. versionadded:: 3.6 |
| 1998 |
See :pep:`529` for more details. |
| 1999 |
|
| 2000 |
.. deprecated-removed:: 3.13 3.16 |
| 2001 |
Use :envvar:`PYTHONLEGACYWINDOWSFSENCODING` instead. |
| 2002 |
|
| 2003 |
.. data:: stdin |
| 2004 |
stdout |
| 2005 |
stderr |
| 2006 |
|
| 2007 |
:term:`File objects <file object>` used by the interpreter for standard |
| 2008 |
input, output and errors: |
| 2009 |
|
| 2010 |
* ``stdin`` is used for all interactive input (including calls to |
| 2011 |
:func:`input`); |
| 2012 |
* ``stdout`` is used for the output of :func:`print` and :term:`expression` |
| 2013 |
statements and for the prompts of :func:`input`; |
| 2014 |
* The interpreter's own prompts and its error messages go to ``stderr``. |
| 2015 |
|
| 2016 |
These streams are regular :term:`text files <text file>` like those |
| 2017 |
returned by the :func:`open` function. Their parameters are chosen as |
| 2018 |
follows: |
| 2019 |
|
| 2020 |
* The encoding and error handling are is initialized from |
| 2021 |
:c:member:`PyConfig.stdio_encoding` and :c:member:`PyConfig.stdio_errors`. |
| 2022 |
|
| 2023 |
On Windows, UTF-8 is used for the console device. Non-character |
| 2024 |
devices such as disk files and pipes use the system locale |
| 2025 |
encoding (i.e. the ANSI codepage). Non-console character |
| 2026 |
devices such as NUL (i.e. where ``isatty()`` returns ``True``) use the |
| 2027 |
value of the console input and output codepages at startup, |
| 2028 |
respectively for stdin and stdout/stderr. This defaults to the |
| 2029 |
system :term:`locale encoding` if the process is not initially attached |
| 2030 |
to a console. |
| 2031 |
|
| 2032 |
The special behaviour of the console can be overridden |
| 2033 |
by setting the environment variable PYTHONLEGACYWINDOWSSTDIO |
| 2034 |
before starting Python. In that case, the console codepages are |
| 2035 |
used as for any other character device. |
| 2036 |
|
| 2037 |
Under all platforms, you can override the character encoding by |
| 2038 |
setting the :envvar:`PYTHONIOENCODING` environment variable before |
| 2039 |
starting Python or by using the new :option:`-X` ``utf8`` command |
| 2040 |
line option and :envvar:`PYTHONUTF8` environment variable. However, |
| 2041 |
for the Windows console, this only applies when |
| 2042 |
:envvar:`PYTHONLEGACYWINDOWSSTDIO` is also set. |
| 2043 |
|
| 2044 |
* When interactive, the ``stdout`` stream is line-buffered. Otherwise, |
| 2045 |
it is block-buffered like regular text files. The ``stderr`` stream |
| 2046 |
is line-buffered in both cases. You can make both streams unbuffered |
| 2047 |
by passing the :option:`-u` command-line option or setting the |
| 2048 |
:envvar:`PYTHONUNBUFFERED` environment variable. |
| 2049 |
|
| 2050 |
.. versionchanged:: 3.9 |
| 2051 |
Non-interactive ``stderr`` is now line-buffered instead of fully |
| 2052 |
buffered. |
| 2053 |
|
| 2054 |
.. note:: |
| 2055 |
|
| 2056 |
To write or read binary data from/to the standard streams, use the |
| 2057 |
underlying binary :data:`~io.TextIOBase.buffer` object. For example, to |
| 2058 |
write bytes to :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``. |
| 2059 |
|
| 2060 |
However, if you are writing a library (and do not control in which |
| 2061 |
context its code will be executed), be aware that the standard streams |
| 2062 |
may be replaced with file-like objects like :class:`io.StringIO` which |
| 2063 |
do not support the :attr:`!buffer` attribute. |
| 2064 |
|
| 2065 |
|
| 2066 |
.. data:: __stdin__ |
| 2067 |
__stdout__ |
| 2068 |
__stderr__ |
| 2069 |
|
| 2070 |
These objects contain the original values of ``stdin``, ``stderr`` and |
| 2071 |
``stdout`` at the start of the program. They are used during finalization, |
| 2072 |
and could be useful to print to the actual standard stream no matter if the |
| 2073 |
``sys.std*`` object has been redirected. |
| 2074 |
|
| 2075 |
It can also be used to restore the actual files to known working file objects |
| 2076 |
in case they have been overwritten with a broken object. However, the |
| 2077 |
preferred way to do this is to explicitly save the previous stream before |
| 2078 |
replacing it, and restore the saved object. |
| 2079 |
|
| 2080 |
.. note:: |
| 2081 |
Under some conditions ``stdin``, ``stdout`` and ``stderr`` as well as the |
| 2082 |
original values ``__stdin__``, ``__stdout__`` and ``__stderr__`` can be |
| 2083 |
``None``. It is usually the case for Windows GUI apps that aren't connected |
| 2084 |
to a console and Python apps started with :program:`pythonw`. |
| 2085 |
|
| 2086 |
|
| 2087 |
.. data:: stdlib_module_names |
| 2088 |
|
| 2089 |
A frozenset of strings containing the names of standard library modules. |
| 2090 |
|
| 2091 |
It is the same on all platforms. Modules which are not available on |
| 2092 |
some platforms and modules disabled at Python build are also listed. |
| 2093 |
All module kinds are listed: pure Python, built-in, frozen and extension |
| 2094 |
modules. Test modules are excluded. |
| 2095 |
|
| 2096 |
For packages, only the main package is listed: sub-packages and sub-modules |
| 2097 |
are not listed. For example, the ``email`` package is listed, but the |
| 2098 |
``email.mime`` sub-package and the ``email.message`` sub-module are not |
| 2099 |
listed. |
| 2100 |
|
| 2101 |
See also the :data:`sys.builtin_module_names` list. |
| 2102 |
|
| 2103 |
.. versionadded:: 3.10 |
| 2104 |
|
| 2105 |
|
| 2106 |
.. data:: thread_info |
| 2107 |
|
| 2108 |
A :term:`named tuple` holding information about the thread |
| 2109 |
implementation. |
| 2110 |
|
| 2111 |
.. attribute:: thread_info.name |
| 2112 |
|
| 2113 |
The name of the thread implementation: |
| 2114 |
|
| 2115 |
* ``"nt"``: Windows threads |
| 2116 |
* ``"pthread"``: POSIX threads |
| 2117 |
* ``"pthread-stubs"``: stub POSIX threads |
| 2118 |
(on WebAssembly platforms without threading support) |
| 2119 |
* ``"solaris"``: Solaris threads |
| 2120 |
|
| 2121 |
.. attribute:: thread_info.lock |
| 2122 |
|
| 2123 |
The name of the lock implementation: |
| 2124 |
|
| 2125 |
* ``"semaphore"``: a lock uses a semaphore |
| 2126 |
* ``"mutex+cond"``: a lock uses a mutex and a condition variable |
| 2127 |
* ``None`` if this information is unknown |
| 2128 |
|
| 2129 |
.. attribute:: thread_info.version |
| 2130 |
|
| 2131 |
The name and version of the thread library. |
| 2132 |
It is a string, or ``None`` if this information is unknown. |
| 2133 |
|
| 2134 |
.. versionadded:: 3.3 |
| 2135 |
|
| 2136 |
|
| 2137 |
.. data:: tracebacklimit |
| 2138 |
|
| 2139 |
When this variable is set to an integer value, it determines the maximum number |
| 2140 |
of levels of traceback information printed when an unhandled exception occurs. |
| 2141 |
The default is ``1000``. When set to ``0`` or less, all traceback information |
| 2142 |
is suppressed and only the exception type and value are printed. |
| 2143 |
|
| 2144 |
|
| 2145 |
.. function:: unraisablehook(unraisable, /) |
| 2146 |
|
| 2147 |
Handle an unraisable exception. |
| 2148 |
|
| 2149 |
Called when an exception has occurred but there is no way for Python to |
| 2150 |
handle it. For example, when a destructor raises an exception or during |
| 2151 |
garbage collection (:func:`gc.collect`). |
| 2152 |
|
| 2153 |
The *unraisable* argument has the following attributes: |
| 2154 |
|
| 2155 |
* :attr:`!exc_type`: Exception type. |
| 2156 |
* :attr:`!exc_value`: Exception value, can be ``None``. |
| 2157 |
* :attr:`!exc_traceback`: Exception traceback, can be ``None``. |
| 2158 |
* :attr:`!err_msg`: Error message, can be ``None``. |
| 2159 |
* :attr:`!object`: Object causing the exception, can be ``None``. |
| 2160 |
|
| 2161 |
The default hook formats :attr:`!err_msg` and :attr:`!object` as: |
| 2162 |
``f'{err_msg}: {object!r}'``; use "Exception ignored in" error message |
| 2163 |
if :attr:`!err_msg` is ``None``. |
| 2164 |
|
| 2165 |
:func:`sys.unraisablehook` can be overridden to control how unraisable |
| 2166 |
exceptions are handled. |
| 2167 |
|
| 2168 |
.. seealso:: |
| 2169 |
|
| 2170 |
:func:`excepthook` which handles uncaught exceptions. |
| 2171 |
|
| 2172 |
.. warning:: |
| 2173 |
|
| 2174 |
Storing :attr:`!exc_value` using a custom hook can create a reference cycle. |
| 2175 |
It should be cleared explicitly to break the reference cycle when the |
| 2176 |
exception is no longer needed. |
| 2177 |
|
| 2178 |
Storing :attr:`!object` using a custom hook can resurrect it if it is set to an |
| 2179 |
object which is being finalized. Avoid storing :attr:`!object` after the custom |
| 2180 |
hook completes to avoid resurrecting objects. |
| 2181 |
|
| 2182 |
.. audit-event:: sys.unraisablehook hook,unraisable sys.unraisablehook |
| 2183 |
|
| 2184 |
Raise an auditing event ``sys.unraisablehook`` with arguments |
| 2185 |
*hook*, *unraisable* when an exception that cannot be handled occurs. |
| 2186 |
The *unraisable* object is the same as what will be passed to the hook. |
| 2187 |
If no hook has been set, *hook* may be ``None``. |
| 2188 |
|
| 2189 |
.. versionadded:: 3.8 |
| 2190 |
|
| 2191 |
.. data:: version |
| 2192 |
|
| 2193 |
A string containing the version number of the Python interpreter plus additional |
| 2194 |
information on the build number and compiler used. This string is displayed |
| 2195 |
when the interactive interpreter is started. Do not extract version information |
| 2196 |
out of it, rather, use :data:`version_info` and the functions provided by the |
| 2197 |
:mod:`platform` module. |
| 2198 |
|
| 2199 |
|
| 2200 |
.. data:: api_version |
| 2201 |
|
| 2202 |
The C API version, equivalent to the C macro :c:macro:`PYTHON_API_VERSION`. |
| 2203 |
Defined for backwards compatibility. |
| 2204 |
|
| 2205 |
Currently, this constant is not updated in new Python versions, and is not |
| 2206 |
useful for versioning. This may change in the future. |
| 2207 |
|
| 2208 |
|
| 2209 |
.. data:: version_info |
| 2210 |
|
| 2211 |
A tuple containing the five components of the version number: *major*, *minor*, |
| 2212 |
*micro*, *releaselevel*, and *serial*. All values except *releaselevel* are |
| 2213 |
integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or |
| 2214 |
``'final'``. The ``version_info`` value corresponding to the Python version 2.0 |
| 2215 |
is ``(2, 0, 0, 'final', 0)``. The components can also be accessed by name, |
| 2216 |
so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major`` |
| 2217 |
and so on. |
| 2218 |
|
| 2219 |
.. versionchanged:: 3.1 |
| 2220 |
Added named component attributes. |
| 2221 |
|
| 2222 |
.. data:: warnoptions |
| 2223 |
|
| 2224 |
This is an implementation detail of the warnings framework; do not modify this |
| 2225 |
value. Refer to the :mod:`warnings` module for more information on the warnings |
| 2226 |
framework. |
| 2227 |
|
| 2228 |
|
| 2229 |
.. data:: winver |
| 2230 |
|
| 2231 |
The version number used to form registry keys on Windows platforms. This is |
| 2232 |
stored as string resource 1000 in the Python DLL. The value is normally the |
| 2233 |
major and minor versions of the running Python interpreter. It is provided in the :mod:`!sys` |
| 2234 |
module for informational purposes; modifying this value has no effect on the |
| 2235 |
registry keys used by Python. |
| 2236 |
|
| 2237 |
.. availability:: Windows. |
| 2238 |
|
| 2239 |
|
| 2240 |
.. data:: monitoring |
| 2241 |
:noindex: |
| 2242 |
|
| 2243 |
Namespace containing functions and constants for register callbacks |
| 2244 |
and controlling monitoring events. |
| 2245 |
See :mod:`sys.monitoring` for details. |
| 2246 |
|
| 2247 |
.. data:: _xoptions |
| 2248 |
|
| 2249 |
A dictionary of the various implementation-specific flags passed through |
| 2250 |
the :option:`-X` command-line option. Option names are either mapped to |
| 2251 |
their values, if given explicitly, or to :const:`True`. Example: |
| 2252 |
|
| 2253 |
.. code-block:: shell-session |
| 2254 |
|
| 2255 |
$ ./python -Xa=b -Xc |
| 2256 |
Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50) |
| 2257 |
[GCC 4.4.3] on linux2 |
| 2258 |
Type "help", "copyright", "credits" or "license" for more information. |
| 2259 |
>>> import sys |
| 2260 |
>>> sys._xoptions |
| 2261 |
{'a': 'b', 'c': True} |
| 2262 |
|
| 2263 |
.. impl-detail:: |
| 2264 |
|
| 2265 |
This is a CPython-specific way of accessing options passed through |
| 2266 |
:option:`-X`. Other implementations may export them through other |
| 2267 |
means, or not at all. |
| 2268 |
|
| 2269 |
.. versionadded:: 3.2 |
| 2270 |
|
| 2271 |
|
| 2272 |
.. rubric:: Citations |
| 2273 |
|
| 2274 |
.. [C99] ISO/IEC 9899:1999. "Programming languages -- C." A public draft of this standard is available at https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf\ . |