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