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.
On POSIX systems where Python is build with the standard configure script, this contains the ABI flags as specified by PEP 3149.
New in version 3.2.
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.
Set during Python startup, before site.py is run, to the same value as exec_prefix. If not running in a virtual environment, the values will stay the same; if site.py finds that a virtual environment is in use, the values of prefix and exec_prefix will be changed to point to the virtual environment, whereas base_prefix and base_exec_prefix will remain pointing to the base Python installation (the one which the virtual environment was created from).
New in version 3.3.
Set during Python startup, before site.py is run, to the same value as prefix. If not running in a virtual environment, the values will stay the same; if site.py finds that a virtual environment is in use, the values of prefix and exec_prefix will be changed to point to the virtual environment, whereas base_prefix and base_exec_prefix will remain pointing to the base Python installation (the one which the virtual environment was created from).
New in version 3.3.
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.
A tuple of strings giving 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.)
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 some other code.
A string containing the copyright pertaining to the Python interpreter.
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.
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.
Print low-level information to stderr about the state of CPython’s memory allocator.
If Python is configured –with-pydebug, it also performs some expensive internal consistency checks.
New in version 3.3.
CPython implementation detail: This function is specific to CPython. The exact output format is not defined here, and may change.
Integer specifying the handle of the Python DLL. Availability: Windows.
If value is not None, this function prints repr(value) to sys.stdout, and saves value in builtins._. If repr(value) is not encodable to sys.stdout.encoding with sys.stdout.errors error handler (which is probably 'strict'), encode it to sys.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 to sys.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 on UnicodeEncodeError.
If this is true, Python won’t try to write .pyc or .pyo files on the import of source modules. This value is initially set to True or False depending on the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable, but you can set it yourself to control bytecode file generation.
This function prints out a given traceback and exception to sys.stderr.
When an exception is raised and uncaught, the interpreter calls sys.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 to sys.excepthook.
These objects contain the original values of displayhook and excepthook at the start of the program. They are saved so that displayhook and excepthook can be restored in case they happen to get replaced with broken objects.
This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible.
If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exception type); traceback gets a traceback object (see the Reference Manual) which encapsulates the call stack at the point where the exception originally occurred.
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. the pyconfig.h header file) are installed in the directory exec_prefix/lib/pythonX.Y/config, and shared library modules are installed in exec_prefix/lib/pythonX.Y/lib-dynload, where X.Y is the version number of Python, for example 3.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, via base_exec_prefix.
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 or None.
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
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 to stderr 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.
The struct sequence flags exposes the status of command line flags. The attributes are read only.
| attribute | flag |
|---|---|
| debug | -d |
| inspect | -i |
| interactive | -i |
| optimize | -O or -OO |
| dont_write_bytecode | -B |
| no_user_site | -s |
| no_site | -S |
| ignore_environment | -E |
| verbose | -v |
| bytes_warning | -b |
| quiet | -q |
| hash_randomization | -R |
Changed in version 3.2: Added quiet attribute for the new -q flag.
New in version 3.2.3: The hash_randomization attribute.
Changed in version 3.3: Removed obsolete division_warning attribute.
A struct sequence 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.
| attribute | float.h macro | explanation |
|---|---|---|
| epsilon | DBL_EPSILON | difference between 1 and the least value greater than 1 that is representable as a float |
| dig | DBL_DIG | maximum number of decimal digits that can be faithfully represented in a float; see below |
| mant_dig | DBL_MANT_DIG | float precision: the number of base-radix digits in the significand of a float |
| max | DBL_MAX | maximum representable finite float |
| max_exp | DBL_MAX_EXP | maximum integer e such that radix**(e-1) is a representable finite float |
| max_10_exp | DBL_MAX_10_EXP | maximum integer e such that 10**e is in the range of representable finite floats |
| min | DBL_MIN | minimum positive normalized float |
| min_exp | DBL_MIN_EXP | minimum integer e such that radix**(e-1) is a normalized float |
| min_10_exp | DBL_MIN_10_EXP | minimum integer e such that 10**e is a normalized float |
| radix | FLT_RADIX | radix of exponent representation |
| rounds | FLT_ROUNDS | integer constant representing the rounding mode used for arithmetic operations. This reflects the value of the system FLT_ROUNDS macro at interpreter startup time. See section 5.2.4.2.2 of the C99 standard for an explanation of the possible values and their meanings. |
The attribute sys.float_info.dig needs further explanation. If s is any string representing a decimal number with at most sys.float_info.dig significant digits, then converting s 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'
A string indicating how the repr() function behaves for floats. If the string has value 'short' then for a finite float x, repr(x) aims to produce a short string with the property that float(repr(x)) == x. This is the usual behaviour in Python 3.1 and later. Otherwise, float_repr_style has value 'legacy' and repr(x) behaves in the same way as it did in versions of Python prior to 3.1.
New in version 3.1.
Return the interpreter’s “check interval”; see setcheckinterval().
Deprecated since version 3.2: Use getswitchinterval() instead.
Return the name of the current default string encoding used by the Unicode implementation.
Return the current value of the flags that are used for dlopen() calls. The flag constants are defined in the ctypes and DLFCN modules. Availability: Unix.
Return the name of the encoding used to convert Unicode filenames into system file names. The result value depends on the operating system:
Changed in version 3.2: getfilesystemencoding() result cannot be None anymore.
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().
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().
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.
Return the interpreter’s “thread switch interval”; see setswitchinterval().
New in version 3.2.
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.
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.
Get the profiler function as set by setprofile().
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.
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, and product_type. service_pack contains a string while all other values are integers. The components can also be accessed by name, so sys.getwindowsversion()[0] is equivalent to sys.getwindowsversion().major. For compatibility with prior versions, only the first 5 elements are retrievable by indexing.
platform may be one of the following values:
| Constant | Platform |
|---|---|
| 0 (VER_PLATFORM_WIN32s) | Win32s on Windows 3.1 |
| 1 (VER_PLATFORM_WIN32_WINDOWS) | Windows 95/98/ME |
| 2 (VER_PLATFORM_WIN32_NT) | Windows NT/2000/XP/x64 |
| 3 (VER_PLATFORM_WIN32_CE) | Windows CE |
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 on OSVERSIONINFOEX() for more information about these fields.
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.
A struct sequence giving parameters of the numeric hash implementation. For more details about hashing of numeric types, see Hashing of numeric types.
| attribute | explanation |
|---|---|
| width | width in bits used for hash values |
| modulus | prime modulus P used for numeric hash scheme |
| inf | hash value returned for a positive infinity |
| nan | hash value returned for a nan |
| imag | multiplier used for the imaginary part of a complex number |
New in version 3.2.
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-in hex() function. The struct sequence sys.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
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, which sys.version_info represents. For example, for PyPy 1.8 sys.implementation.version might be sys.version_info(1, 8, 0, 'final', 0), whereas sys.version_info would be sys.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. If cache_tag is set to None, it indicates that module caching should be disabled.