27.1. 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.
-
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-ccommand 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
fileinputmodule.
-
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 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.)
-
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 some other code.
-
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.
-
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
tracebackmodule 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.
-
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.encodingwithsys.stdout.errorserror handler (which is probably'strict'), encode it tosys.stdout.encodingwith'backslashreplace'error handler.sys.displayhookis 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:
Changed in version 3.2: Use
'backslashreplace'error handler onUnicodeEncodeError.
-
sys.excepthook(type, value, traceback)¶ This function prints out a given traceback and exception to
sys.stderr.When an exception is raised and uncaught, the interpreter calls
sys.excepthookwith 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.
-
sys.__displayhook__¶ -
sys.__excepthook__¶ These objects contain the original values of
displayhookandexcepthookat the start of the program. They are saved so thatdisplayhookandexcepthookcan be restored in case they happen to get replaced with broken objects.
-
sys.exc_info()¶ 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
Nonevalues is returned. Otherwise, the values returned are(type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass ofBaseException); 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.Warning
Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. Since most functions don’t need access to the traceback, the best solution is to use something like
exctype, value = sys.exc_info()[:2]to extract only the exception type and value. If you do need the traceback, make sure to delete it after use (best done with atry...finallystatement) or to callexc_info()in a function that does not itself handle an exception.Such cycles are normally automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.
-
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-prefixargument to the configure script. Specifically, all configuration files (e.g. thepyconfig.hheader file) are installed in the directoryexec_prefix + '/lib/pythonversion/config', and shared library modules are installed inexec_prefix + '/lib/pythonversion/lib-dynload', where version is equal toversion[:3].
-
sys.executable¶ A string giving the name of the executable binary for the Python interpreter, on systems where this makes sense.
-
sys.exit([arg])¶ Exit from Python. This is implemented by raising the
SystemExitexception, so cleanup actions specified by finally clauses oftrystatements 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,
Noneis equivalent to passing zero, and any other object is printed tostderrand 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.
-
sys.flags¶ The struct sequence flags exposes the status of command line flags. The attributes are read only.
attribute flag debug-ddivision_warning-Qinspect-iinteractive-ioptimize-Oor-OOdont_write_bytecode-Bno_user_site-sno_site-Signore_environment-Everbose-vbytes_warning-bquiet-qChanged in version 3.2:
Changed in version 3.2: Added
quietattribute for the new-qflag.
-
sys.float_info¶ A structseq 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.hfor 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 epsilonDBL_EPSILON difference between 1 and the least value greater than 1 that is representable as a float digDBL_DIG maximum number of decimal digits that can be faithfully represented in a float; see below mant_digDBL_MANT_DIG float precision: the number of base- radixdigits in the significand of a floatmaxDBL_MAX maximum representable finite float max_expDBL_MAX_EXP maximum integer e such that radix**(e-1)is a representable finite floatmax_10_expDBL_MAX_10_EXP maximum integer e such that 10**eis in the range of representable finite floatsminDBL_MIN minimum positive normalized float min_expDBL_MIN_EXP minimum integer e such that radix**(e-1)is a normalized floatmin_10_expDBL_MIN_10_EXP minimum integer e such that 10**eis a normalized floatradixFLT_RADIX radix of exponent representation roundsFLT_ROUNDS constant representing rounding mode used for arithmetic operations The attribute
sys.float_info.digneeds further explanation. Ifsis any string representing a decimal number with at mostsys.float_info.digsignificant digits, then convertingsto 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.digsignificant 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_stylehas value'legacy'andrepr(x)behaves in the same way as it did in versions of Python prior to 3.1.New in version 3.1:
New in version 3.1.
-
sys.getcheckinterval()¶ Return the interpreter’s “check interval”; see
setcheckinterval().Deprecated since version 3.2:
Deprecated since version 3.2: Use
getswitchinterval()instead.
-
sys.getdefaultencoding()¶ Return the name of the current default string encoding used by the Unicode implementation.
-
sys.getdlopenflags()¶ Return the current value of the flags that are used for
dlopen()calls. The flag constants are defined in thectypesandDLFCNmodules. Availability: Unix.
-
sys.getfilesystemencoding()¶ Return the name of the encoding used to convert Unicode filenames into system file names. The result value depends on the operating system:
- On Mac OS X, the encoding is
'utf-8'. - On Unix, the encoding is the user’s preference according to the result of
nl_langinfo(CODESET), or
'utf-8'ifnl_langinfo(CODESET)failed. - On Windows NT+, file names are Unicode natively, so no conversion is
performed.
getfilesystemencoding()still returns'mbcs', as this is the encoding that applications should use when they explicitly want to convert Unicode strings to byte strings that are equivalent when used as file names. - On Windows 9x, the encoding is
'mbcs'.
Changed in version 3.2:
Changed in version 3.2: On Unix, use
'utf-8'instead ofNoneifnl_langinfo(CODESET)failed.getfilesystemencoding()result cannot beNone.- On Mac OS X, the encoding is