sys
— System-specific parameters and functions¶
This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. Unless explicitly noted otherwise, all variables are read-only.
- sys.abiflags¶
On POSIX systems where Python was built with the standard
configure
script, this contains the ABI flags as specified by PEP 3149.Added in version 3.2.
Changed in version 3.8: Default flags became an empty string (
m
flag for pymalloc has been removed).Availability: Unix.
- sys.addaudithook(hook)¶
Append the callable hook to the list of active auditing hooks for the current (sub)interpreter.
When an auditing event is raised through the
sys.audit()
function, each hook will be called in the order it was added with the event name and the tuple of arguments. Native hooks added byPySys_AddAuditHook()
are called first, followed by hooks added in the current (sub)interpreter. Hooks can then log the event, raise an exception to abort the operation, or terminate the process entirely.Note that audit hooks are primarily for collecting information about internal or otherwise unobservable actions, whether by Python or libraries written in Python. They are not suitable for implementing a “sandbox”. In particular, malicious code can trivially disable or bypass hooks added using this function. At a minimum, any security-sensitive hooks must be added using the C API
PySys_AddAuditHook()
before initialising the runtime, and any modules allowing arbitrary memory modification (such asctypes
) should be completely removed or closely monitored.Calling
sys.addaudithook()
will itself raise an auditing event namedsys.addaudithook
with no arguments. If any existing hooks raise an exception derived fromRuntimeError
, the new hook will not be added and the exception suppressed. As a result, callers cannot assume that their hook has been added unless they control all existing hooks.See the audit events table for all events raised by CPython, and PEP 578 for the original design discussion.
Added in version 3.8.
Changed in version 3.8.1: Exceptions derived from
Exception
but notRuntimeError
are no longer suppressed.CPython implementation detail: When tracing is enabled (see
settrace()
), Python hooks are only traced if the callable has a__cantrace__
member that is set to a true value. Otherwise, trace functions will skip the hook.
- sys.argv¶
The list of command line arguments passed to a Python script.
argv[0]
is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the-c
command line option to the interpreter,argv[0]
is set to the string'-c'
. If no script name was passed to the Python interpreter,argv[0]
is the empty string.To loop over the standard input, or the list of files given on the command line, see the
fileinput
module.See also
sys.orig_argv
.Note
On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes, you can get it by
[os.fsencode(arg) for arg in sys.argv]
.
- sys.audit(event, *args)¶
Raise an auditing event and trigger any active auditing hooks. event is a string identifying the event, and args may contain optional arguments with more information about the event. The number and types of arguments for a given event are considered a public and stable API and should not be modified between releases.
For example, one auditing event is named
os.chdir
. This event has one argument called path that will contain the requested new working directory.sys.audit()
will call the existing auditing hooks, passing the event name and arguments, and will re-raise the first exception from any hook. In general, if an exception is raised, it should not be handled and the process should be terminated as quickly as possible. This allows hook implementations to decide how to respond to particular events: they can merely log the event or abort the operation by raising an exception.Hooks are added using the
sys.addaudithook()
orPySys_AddAuditHook()
functions.The native equivalent of this function is
PySys_Audit()
. Using the native function is preferred when possible.See the audit events table for all events raised by CPython.
Added in version 3.8.
- sys.base_exec_prefix¶
Set during Python startup, before
site.py
is run, to the same value asexec_prefix
. If not running in a virtual environment, the values will stay the same; ifsite.py
finds that a virtual environment is in use, the values ofprefix
andexec_prefix
will be changed to point to the virtual environment, whereasbase_prefix
andbase_exec_prefix
will remain pointing to the base Python installation (the one which the virtual environment was created from).Added in version 3.3.
- sys.base_prefix¶
Set during Python startup, before
site.py
is run, to the same value asprefix
. If not running in a virtual environment, the values will stay the same; ifsite.py
finds that a virtual environment is in use, the values ofprefix
andexec_prefix
will be changed to point to the virtual environment, whereasbase_prefix
andbase_exec_prefix
will remain pointing to the base Python installation (the one which the virtual environment was created from).Added in version 3.3.
- sys.byteorder¶
An indicator of the native byte order. This will have the value
'big'
on big-endian (most-significant byte first) platforms, and'little'
on little-endian (least-significant byte first) platforms.
- sys.builtin_module_names¶
A tuple of strings containing the names of all modules that are compiled into this Python interpreter. (This information is not available in any other way —
modules.keys()
only lists the imported modules.)See also the
sys.stdlib_module_names
list.
- sys.call_tracing(func, args)¶
Call
func(*args)
, while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug or profile some other code.Tracing is suspended while calling a tracing function set by
settrace()
orsetprofile()
to avoid infinite recursion.call_tracing()
enables explicit recursion of the tracing function.
- sys.copyright¶
A string containing the copyright pertaining to the Python interpreter.
- sys._clear_type_cache()¶
Clear the internal type cache. The type cache is used to speed up attribute and method lookups. Use the function only to drop unnecessary references during reference leak debugging.
This function should be used for internal and specialized purposes only.
Deprecated since version 3.13: Use the more general
_clear_internal_caches()
function instead.
- sys._clear_internal_caches()¶
Clear all internal performance-related caches. Use this function only to release unnecessary references and memory blocks when hunting for leaks.
Added in version 3.13.
- sys._current_frames()¶
Return a dictionary mapping each thread’s identifier to the topmost stack frame currently active in that thread at the time the function is called. Note that functions in the
traceback
module can build the call stack given such a frame.This is most useful for debugging deadlock: this function does not require the deadlocked threads’ cooperation, and such threads’ call stacks are frozen for as long as they remain deadlocked. The frame returned for a non-deadlocked thread may bear no relationship to that thread’s current activity by the time calling code examines the frame.
This function should be used for internal and specialized purposes only.
Raises an auditing event
sys._current_frames
with no arguments.
- sys._current_exceptions()¶
Return a dictionary mapping each thread’s identifier to the topmost exception currently active in that thread at the time the function is called. If a thread is not currently handling an exception, it is not included in the result dictionary.
This is most useful for statistical profiling.
This function should be used for internal and specialized purposes only.
Raises an auditing event
sys._current_exceptions
with no arguments.Changed in version 3.12: Each value in the dictionary is now a single exception instance, rather than a 3-tuple as returned from
sys.exc_info()
.
- sys.breakpointhook()¶
This hook function is called by built-in
breakpoint()
. By default, it drops you into thepdb
debugger, but it can be set to any other function so that you can choose which debugger gets used.The signature of this function is dependent on what it calls. For example, the default binding (e.g.
pdb.set_trace()
) expects no arguments, but you might bind it to a function that expects additional arguments (positional and/or keyword). The built-inbreakpoint()
function passes its*args
and**kws
straight through. Whateverbreakpointhooks()
returns is returned frombreakpoint()
.The default implementation first consults the environment variable
PYTHONBREAKPOINT
. If that is set to"0"
then this function returns immediately; i.e. it is a no-op. If the environment variable is not set, or is set to the empty string,pdb.set_trace()
is called. Otherwise this variable should name a function to run, using Python’s dotted-import nomenclature, e.g.package.subpackage.module.function
. In this case,package.subpackage.module
would be imported and the resulting module must have a callable namedfunction()
. This is run, passing in*args
and**kws
, and whateverfunction()
returns,sys.breakpointhook()
returns to the built-inbreakpoint()
function.Note that if anything goes wrong while importing the callable named by
PYTHONBREAKPOINT
, aRuntimeWarning
is reported and the breakpoint is ignored.Also note that if
sys.breakpointhook()
is overridden programmatically,PYTHONBREAKPOINT
is not consulted.Added in version 3.7.
- sys._debugmallocstats()¶
Print low-level information to stderr about the state of CPython’s memory allocator.
If Python is built in debug mode (
configure --with-pydebug option
), it also performs some expensive internal consistency checks.Added in version 3.3.
CPython implementation detail: This function is specific to CPython. The exact output format is not defined here, and may change.
- sys.dllhandle¶
Integer specifying the handle of the Python DLL.
Availability: Windows.
- sys.displayhook(value)¶
If value is not
None
, this function printsrepr(value)
tosys.stdout
, and saves value inbuiltins._
. Ifrepr(value)
is not encodable tosys.stdout.encoding
withsys.stdout.errors
error handler (which is probably'strict'
), encode it tosys.stdout.encoding
with'backslashreplace'
error handler.sys.displayhook
is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function tosys.displayhook
.Pseudo-code:
def displayhook(value): if value is None: return # Set '_' to None to avoid recursion builtins._ = None text = repr(value) try: sys.stdout.write(text) except UnicodeEncodeError: bytes = text.encode(sys.stdout.encoding, 'backslashreplace') if hasattr(sys.stdout, 'buffer'): sys.stdout.buffer.write(bytes) else: text = bytes.decode(sys.stdout.encoding, 'strict') sys.stdout.write(text) sys.stdout.write("\n") builtins._ = value
Changed in version 3.2: Use
'backslashreplace'
error handler onUnicodeEncodeError
.
- sys.dont_write_bytecode¶
If this is true, Python won’t try to write
.pyc
files on the import of source modules. This value is initially set toTrue
orFalse
depending on the-B
command line option and thePYTHONDONTWRITEBYTECODE
environment variable, but you can set it yourself to control bytecode file generation.
- sys._emscripten_info¶
A named tuple holding information about the environment on the wasm32-emscripten platform. The named tuple is provisional and may change in the future.
- _emscripten_info.emscripten_version¶
Emscripten version as tuple of ints (major, minor, micro), e.g.
(3, 1, 8)
.
- _emscripten_info.runtime¶
Runtime string, e.g. browser user agent,
'Node.js v14.18.2'
, or'UNKNOWN'
.
- _emscripten_info.pthreads¶
True
if Python is compiled with Emscripten pthreads support.
True
if Python is compiled with shared memory support.
Availability: Emscripten.
Added in version 3.11.
- sys.pycache_prefix¶
If this is set (not
None
), Python will write bytecode-cache.pyc
files to (and read them from) a parallel directory tree rooted at this directory, rather than from__pycache__
directories in the source code tree. Any__pycache__
directories in the source code tree will be ignored and new.pyc
files written within the pycache prefix. Thus if you usecompileall
as a pre-build step, you must ensure you run it with the same pycache prefix (if any) that you will use at runtime.A relative path is interpreted relative to the current working directory.
This value is initially set based on the value of the
-X
pycache_prefix=PATH
command-line option or thePYTHONPYCACHEPREFIX
environment variable (command-line takes precedence). If neither are set, it isNone
.Added in version 3.8.
- sys.excepthook(type, value, traceback)¶
This function prints out a given traceback and exception to
sys.stderr
.When an exception other than
SystemExit
is raised and uncaught, the interpreter callssys.excepthook
with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function tosys.excepthook
.Raise an auditing event
sys.excepthook
with argumentshook
,type
,value
,traceback
when an uncaught exception occurs. If no hook has been set,hook
may beNone
. If any hook raises an exception derived fromRuntimeError
the call to the hook will be suppressed. Otherwise, the audit hook exception will be reported as unraisable andsys.excepthook
will be called.See also
The
sys.unraisablehook()
function handles unraisable exceptions and thethreading.excepthook()
function handles exception raised bythreading.Thread.run()
.
- sys.__breakpointhook__¶
- sys.__displayhook__¶
- sys.__excepthook__¶
- sys.__unraisablehook__¶
These objects contain the original values of
breakpointhook
,displayhook
,excepthook
, andunraisablehook
at the start of the program. They are saved so thatbreakpointhook
,displayhook
andexcepthook
,unraisablehook
can be restored in case they happen to get replaced with broken or alternative objects.Added in version 3.7: __breakpointhook__
Added in version 3.8: __unraisablehook__
- sys.exception()¶
This function, when called while an exception handler is executing (such as an
except
orexcept*
clause), returns the exception instance that was caught by this handler. When exception handlers are nested within one another, only the exception handled by the innermost handler is accessible.If no exception handler is executing, this function returns
None
.Added in version 3.11.
- sys.exc_info()¶
This function returns the old-style representation of the handled exception. If an exception
e
is currently handled (soexception()
would returne
),exc_info()
returns the tuple(type(e), e, e.__traceback__)
. That is, a tuple containing the type of the exception (a subclass ofBaseException
), the exception itself, and a traceback object which typically encapsulates the call stack at the point where the exception last occurred.If no exception is being handled anywhere on the stack, this function return a tuple containing three
None
values.Changed in version 3.11: The
type
andtraceback
fields are now derived from thevalue
(the exception instance), so when an exception is modified while it is being handled, the changes are reflected in the results of subsequent calls toexc_info()
.
- sys.exec_prefix¶
A string giving the site-specific directory prefix where the platform-dependent Python files are installed; by default, this is also
'/usr/local'
. This can be set at build time with the--exec-prefix
argument to the configure script. Specifically, all configuration files (e.g. thepyconfig.h
header file) are installed in the directoryexec_prefix/lib/pythonX.Y/config
, and shared library modules are installed inexec_prefix/lib/pythonX.Y/lib-dynload
, where X.Y is the version number of Python, for example3.2
.Note
If a virtual environment is in effect, this value will be changed in
site.py
to point to the virtual environment. The value for the Python installation will still be available, viabase_exec_prefix
.
- sys.executable¶
A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable,
sys.executable
will be an empty string orNone
.
- sys.exit([arg])¶
Raise a
SystemExit
exception, signaling an intention to exit the interpreter.The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed,
None
is equivalent to passing zero, and any other object is printed tostderr
and results in an exit code of 1. In particular,sys.exit("some error message")
is a quick way to exit a program when an error occurs.Since
exit()
ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. Cleanup actions specified by finally clauses oftry
statements are honored, and it is possible to intercept the exit attempt at an outer level.Changed in version 3.6: If an error occurs in the cleanup after the Python interpreter has caught
SystemExit
(such as an error flushing buffered data in the standard streams), the exit status is changed to 120.
- sys.flags¶
The named tuple flags exposes the status of command line flags. The attributes are read only.
- flags.debug¶
- flags.inspect¶
- flags.interactive¶
- flags.isolated¶
- flags.optimize¶
- flags.dont_write_bytecode¶
- flags.no_user_site¶
- flags.no_site¶
- flags.ignore_environment¶
- flags.verbose¶
- flags.bytes_warning¶
- flags.quiet¶
- flags.hash_randomization¶
- flags.dev_mode¶
- flags.utf8_mode¶
- flags.safe_path¶
- flags.int_max_str_digits¶
-X int_max_str_digits
(integer string conversion length limitation)- flags.warn_default_encoding¶
Changed in version 3.2: Added
quiet
attribute for the new-q
flag.Added in version 3.2.3: The
hash_randomization
attribute.Changed in version 3.3: Removed obsolete
division_warning
attribute.Changed in version 3.4: Added
isolated
attribute for-I
isolated
flag.Changed in version 3.7: Added the
dev_mode
attribute for the new Python Development Mode and theutf8_mode
attribute for the new-X
utf8
flag.Changed in version 3.10: Added
warn_default_encoding
attribute for-X
warn_default_encoding
flag.Changed in version 3.11: Added the
safe_path
attribute for-P
option.Changed in version 3.11: Added the
int_max_str_digits
attribute.
- sys.float_info¶
A named tuple holding information about the float type. It contains low level information about the precision and internal representation. The values correspond to the various floating-point constants defined in the standard header file
float.h
for the ‘C’ programming language; see section 5.2.4.2.2 of the 1999 ISO/IEC C standard [C99], ‘Characteristics of floating types’, for details.Attributes of the float_info
named tuple¶attribute
float.h macro
explanation
- float_info.epsilon¶
DBL_EPSILON
difference between 1.0 and the least value greater than 1.0 that is representable as a float.
See also
math.ulp()
.- float_info.dig¶
DBL_DIG
The maximum number of decimal digits that can be faithfully represented in a float; see below.
- float_info.mant_dig¶
DBL_MANT_DIG
Float precision: the number of base-
radix
digits in the significand of a float.- float_info.max¶
DBL_MAX
The maximum representable positive finite float.
- float_info.max_exp¶
DBL_MAX_EXP
The maximum integer e such that
radix**(e-1)
is a representable finite float.- float_info.max_10_exp¶
DBL_MAX_10_EXP
The maximum integer e such that
10**e
is in the range of representable finite floats.- float_info.min¶
DBL_MIN
The minimum representable positive normalized float.
Use
math.ulp(0.0)
to get the smallest positive denormalized representable float.- float_info.min_exp¶
DBL_MIN_EXP
The minimum integer e such that
radix**(e-1)
is a normalized float.- float_info.min_10_exp¶
DBL_MIN_10_EXP
The minimum integer e such that
10**e
is a normalized float.- float_info.radix¶
FLT_RADIX
The radix of exponent representation.
- float_info.rounds¶
FLT_ROUNDS
An integer representing the rounding mode for floating-point arithmetic. This reflects the value of the system
FLT_ROUNDS
macro at interpreter startup time:-1
: indeterminable0
: toward zero1
: to nearest2
: toward positive infinity3
: toward negative infinity
All other values for
FLT_ROUNDS
characterize implementation-defined rounding behavior.The attribute
sys.float_info.dig
needs further explanation. Ifs
is any string representing a decimal number with at mostsys.float_info.dig
significant digits, then convertings
to a float and back again will recover a string representing the same decimal value:>>> import sys >>> sys.float_info.dig 15 >>> s = '3.14159265358979' # decimal string with 15 significant digits >>> format(float(s), '.15g') # convert to float and back -> same value '3.14159265358979'
But for strings with more than
sys.float_info.dig
significant digits, this isn’t always true:>>> s = '9876543211234567' # 16 significant digits is too many! >>> format(float(s), '.16g') # conversion changes value '9876543211234568'
- sys.float_repr_style¶
A string indicating how the
repr()
function behaves for floats. If the string has value'short'
then for a finite floatx
,repr(x)
aims to produce a short string with the property thatfloat(repr(x)) == x
. This is the usual behaviour in Python 3.1 and later. Otherwise,float_repr_style
has value'legacy'
andrepr(x)
behaves in the same way as it did in versions of Python prior to 3.1.Added in version 3.1.
- sys.getallocatedblocks()¶
Return the number of memory blocks currently allocated by the interpreter, regardless of their size. This function is mainly useful for tracking and debugging memory leaks. Because of the interpreter’s internal caches, the result can vary from call to call; you may have to call
_clear_internal_caches()
andgc.collect()
to get more predictable results.If a Python build or implementation cannot reasonably compute this information,
getallocatedblocks()
is allowed to return 0 instead.Added in version 3.4.
- sys.getunicodeinternedsize()¶
Return the number of unicode objects that have been interned.
Added in version 3.12.
- sys.getandroidapilevel()¶
Return the build-time API level of Android as an integer. This represents the minimum version of Android this build of Python can run on. For runtime version information, see
platform.android_ver()
.Availability: Android.
Added in version 3.7.
- sys.getdefaultencoding()¶
Return
'utf-8'
. This is the name of the default string encoding, used in methods likestr.encode()
.
- sys.getdlopenflags()¶
Return the current value of the flags that are used for
dlopen()
calls. Symbolic names for the flag values can be found in theos
module (RTLD_xxx
constants, e.g.os.RTLD_LAZY
).Availability: Unix.
- sys.getfilesystemencoding()¶
Get the filesystem encoding: the encoding used with the filesystem error handler to convert between Unicode filenames and bytes filenames. The filesystem error handler is returned from
getfilesystemencodeerrors()
.For best compatibility, str should be used for filenames in all cases, although representing filenames as bytes is also supported. Functions accepting or returning filenames should support either str or bytes and internally convert to the system’s preferred representation.
os.fsencode()
andos.fsdecode()
should be used to ensure that the correct encoding and errors mode are used.The filesystem encoding and error handler are configured at Python startup by the
PyConfig_Read()
function: seefilesystem_encoding
andfilesystem_errors
members ofPyConfig
.Changed in version 3.2:
getfilesystemencoding()
result cannot beNone
anymore.Changed in version 3.6: Windows is no longer guaranteed to return
'mbcs'
. See PEP 529 and_enablelegacywindowsfsencoding()
for more information.Changed in version 3.7: Return
'utf-8'
if the Python UTF-8 Mode is enabled.
- sys.getfilesystemencodeerrors()¶
Get the filesystem error handler: the error handler used with the filesystem encoding to convert between Unicode filenames and bytes filenames. The filesystem encoding is returned from
getfilesystemencoding()
.os.fsencode()
andos.fsdecode()
should be used to ensure that the correct encoding and errors mode are used.The filesystem encoding and error handler are configured at Python startup by the
PyConfig_Read()
function: seefilesystem_encoding
andfilesystem_errors
members ofPyConfig
.Added in version 3.6.
- sys.get_int_max_str_digits()¶
Returns the current value for the integer string conversion length limitation. See also
set_int_max_str_digits()
.Added in version 3.11.
- sys.getrefcount(object)¶
Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to
getrefcount()
.Note that the returned value may not actually reflect how many references to the object are actually held. For example, some objects are immortal and have a very high refcount that does not reflect the actual number of references. Consequently, do not rely on the returned value to be accurate, other than a value of 0 or 1.
Changed in version 3.12: Immortal objects have very large refcounts that do not match the actual number of references to the object.
- sys.getrecursionlimit()¶
Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by
setrecursionlimit()
.
- sys.getsizeof(object[, default])¶
Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
If given, default will be returned if the object does not provide means to retrieve the size. Otherwise a
TypeError
will be raised.getsizeof()
calls the object’s__sizeof__
method and adds an additional garbage collector overhead if the object is managed by the garbage collector.See recursive sizeof recipe for an example of using
getsizeof()
recursively to find the size of containers and all their contents.
- sys.getswitchinterval()¶
Return the interpreter’s “thread switch interval” in seconds; see
setswitchinterval()
.Added in version 3.2.
- sys._getframe([depth])¶
Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack,
ValueError
is raised. The default for depth is zero, returning the frame at the top of the call stack.Raises an auditing event
sys._getframe
with argumentframe
.CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.
- sys._getframemodulename([depth])¶
Return the name of a module from the call stack. If optional integer depth is given, return the module that many calls below the top of the stack. If that is deeper than the call stack, or if the module is unidentifiable,
None
is returned. The default for depth is zero, returning the module at the top of the call stack.Raises an auditing event
sys._getframemodulename
with argumentdepth
.CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.
Added in version 3.12.
- sys.getobjects(limit[, type])¶
This function only exists if CPython was built using the specialized configure option
--with-trace-refs
. It is intended only for debugging garbage-collection issues.Return a list of up to limit dynamically allocated Python objects. If type is given, only objects of that exact type (not subtypes) are included.
Objects from the list are not safe to use. Specifically, the result will include objects from all interpreters that share their object allocator state (that is, ones created with
PyInterpreterConfig.use_main_obmalloc
set to 1 or usingPy_NewInterpreter()
, and the main interpreter). Mixing objects from different interpreters may lead to crashes or other unexpected behavior.CPython implementation detail: This function should be used for specialized purposes only. It is not guaranteed to exist in all implementations of Python.
Changed in version 3.13.1: The result may include objects from other interpreters.
- sys.getprofile()¶
Get the profiler function as set by
setprofile()
.
- sys.gettrace()¶
Get the trace function as set by
settrace()
.CPython implementation detail: The
gettrace()
function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations.
- sys.getwindowsversion()¶
Return a named tuple describing the Windows version currently running. The named elements are major, minor, build, platform, service_pack, service_pack_minor, service_pack_major, suite_mask, product_type and platform_version. service_pack contains a string, platform_version a 3-tuple and all other values are integers. The components can also be accessed by name, so
sys.getwindowsversion()[0]
is equivalent tosys.getwindowsversion().major
. For compatibility with prior versions, only the first 5 elements are retrievable by indexing.platform will be
2
(VER_PLATFORM_WIN32_NT).product_type may be one of the following values:
Constant
Meaning
1
(VER_NT_WORKSTATION)The system is a workstation.
2
(VER_NT_DOMAIN_CONTROLLER)The system is a domain controller.
3
(VER_NT_SERVER)The system is a server, but not a domain controller.
This function wraps the Win32
GetVersionEx()
function; see the Microsoft documentation onOSVERSIONINFOEX()
for more information about these fields.platform_version returns the major version, minor version and build number of the current operating system, rather than the version that is being emulated for the process. It is intended for use in logging rather than for feature detection.
Note
platform_version derives the version from kernel32.dll which can be of a different version than the OS version. Please use
platform
module for achieving accurate OS version.Availability: Windows.
Changed in version 3.2: Changed to a named tuple and added service_pack_minor, service_pack_major, suite_mask, and product_type.
Changed in version 3.6: Added platform_version
- sys.get_asyncgen_hooks()¶
Returns an asyncgen_hooks object, which is similar to a
namedtuple
of the form(firstiter, finalizer)
, where firstiter and finalizer are expected to be eitherNone
or functions which take an asynchronous generator iterator as an argument, and are used to schedule finalization of an asynchronous generator by an event loop.Added in version 3.6: See PEP 525 for more details.
Note
This function has been added on a provisional basis (see PEP 411 for details.)
- sys.get_coroutine_origin_tracking_depth()¶
Get the current coroutine origin tracking depth, as set by
set_coroutine_origin_tracking_depth()
.Added in version 3.7.
Note
This function has been added on a provisional basis (see PEP 411 for details.) Use it only for debugging purposes.
- sys.hash_info¶
A named tuple giving parameters of the numeric hash implementation. For more details about hashing of numeric types, see Hashing of numeric types.
- hash_info.width¶
The width in bits used for hash values
- hash_info.modulus¶
The prime modulus P used for numeric hash scheme
- hash_info.inf¶
The hash value returned for a positive infinity
- hash_info.nan¶
(This attribute is no longer used)
- hash_info.imag¶
The multiplier used for the imaginary part of a complex number
- hash_info.algorithm¶
The name of the algorithm for hashing of str, bytes, and memoryview
- hash_info.hash_bits¶
The internal output size of the hash algorithm
- hash_info.seed_bits¶
The size of the seed key of the hash algorithm
Added in version 3.2.
Changed in version 3.4: Added algorithm, hash_bits and seed_bits
- sys.hexversion¶
The version number encoded as a single integer. This is guaranteed to increase with each version, including proper support for non-production releases. For example, to test that the Python interpreter is at least version 1.5.2, use:
if sys.hexversion >= 0x010502F0: # use some advanced feature ... else: # use an alternative implementation or warn the user ...
This is called
hexversion
since it only really looks meaningful when viewed as the result of passing it to the built-inhex()
function. The named tuplesys.version_info
may be used for a more human-friendly encoding of the same information.More details of
hexversion
can be found at API and ABI Versioning.
- sys.implementation¶
An object containing information about the implementation of the currently running Python interpreter. The following attributes are required to exist in all Python implementations.
name is the implementation’s identifier, e.g.
'cpython'
. The actual string is defined by the Python implementation, but it is guaranteed to be lower case.version is a named tuple, in the same format as
sys.version_info
. It represents the version of the Python implementation. This has a distinct meaning from the specific version of the Python language to which the currently running interpreter conforms, whichsys.version_info
represents. For example, for PyPy 1.8sys.implementation.version
might besys.version_info(1, 8, 0, 'final', 0)
, whereassys.version_info
would besys.version_info(2, 7, 2, 'final', 0)
. For CPython they are the same value, since it is the reference implementation.hexversion is the implementation version in hexadecimal format, like
sys.hexversion
.cache_tag is the tag used by the import machinery in the filenames of cached modules. By convention, it would be a composite of the implementation’s name and version, like
'cpython-33'
. However, a Python implementation may use some other value if appropriate. Ifcache_tag
is set toNone
, it indicates that module caching should be disabled.sys.implementation
may contain additional attributes specific to the Python implementation. These non-standard attributes must start with an underscore, and are not described here. Regardless of its contents,