30.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.abiflags¶ On POSIX systems where Python was built with the standard
configurescript, this contains the ABI flags as specified by PEP 3149.3.2 版新加入.
-
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.base_exec_prefix¶ Set during Python startup, before
site.pyis run, to the same value asexec_prefix. If not running in a virtual environment, the values will stay the same; ifsite.pyfinds that a virtual environment is in use, the values ofprefixandexec_prefixwill be changed to point to the virtual environment, whereasbase_prefixandbase_exec_prefixwill remain pointing to the base Python installation (the one which the virtual environment was created from).3.3 版新加入.
-
sys.base_prefix¶ Set during Python startup, before
site.pyis run, to the same value asprefix. If not running in a virtual environment, the values will stay the same; ifsite.pyfinds that a virtual environment is in use, the values ofprefixandexec_prefixwill be changed to point to the virtual environment, whereasbase_prefixandbase_exec_prefixwill remain pointing to the base Python installation (the one which the virtual environment was created from).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 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.breakpointhook()¶ This hook function is called by built-in
breakpoint(). By default, it drops you into thepdbdebugger, 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*argsand**kwsstraight 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.modulewould be imported and the resulting module must have a callable namedfunction(). This is run, passing in*argsand**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, aRuntimeWarningis reported and the breakpoint is ignored.Also note that if
sys.breakpointhook()is overridden programmatically,PYTHONBREAKPOINTis not consulted.3.7 版新加入.
-
sys._debugmallocstats()¶ 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.
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.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
3.2 版更變: Use
'backslashreplace'error handler onUnicodeEncodeError.
-
sys.dont_write_bytecode¶ If this is true, Python won’t try to write
.pycfiles on the import of source modules. This value is initially set toTrueorFalsedepending on the-Bcommand line option and thePYTHONDONTWRITEBYTECODEenvironment variable, but you can set it yourself to control bytecode file generation.
-
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.__breakpointhook__¶ -
sys.__displayhook__¶ -
sys.__excepthook__¶ These objects contain the original values of
breakpointhook,displayhook, andexcepthookat the start of the program. They are saved so thatbreakpointhook,displayhookandexcepthookcan be restored in case they happen to get replaced with broken or alternative objects.3.7 版新加入: __breakpointhook__
-
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.
-
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/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.備註
If a virtual environment is in effect, this value will be changed in
site.pyto 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.executablewill be an empty string orNone.
-
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.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.3.7 版更變: Added
utf8_modeattribute for the new-Xutf8flag.
-
sys.flags¶ The struct sequence flags exposes the status of command line flags. The attributes are read only.
attribute flag debug-dinspect-iinteractive-ioptimize-Oor-OOdont_write_bytecode-Bno_user_site-sno_site-Signore_environment-Everbose-vbytes_warning-bquiet-qhash_randomization-Rdev_mode-Xdevutf8_mode-Xutf83.2 版更變: Added
quietattribute for the new-qflag.3.2.3 版新加入: The
hash_randomizationattribute.3.3 版更變: Removed obsolete
division_warningattribute.
-
sys.float_info¶ 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.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 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.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.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_type_cache()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.3.4 版新加入.
-
sys.getandroidapilevel()¶ Return the build time API version of Android as an integer.
Availability: Android.
3.7 版新加入.
-
sys.getcheckinterval()¶ Return the interpreter’s 「check interval」; see
setcheckinterval().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. Symbolic names for the flag values can be found in theosmodule (RTLD_xxxconstants, e.g.os.RTLD_LAZY). Availability: Unix.
-
sys.getfilesystemencoding()¶ Return the name of the encoding used to convert between Unicode filenames and bytes filenames. 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.
This encoding is always ASCII-compatible.
os.fsencode()andos.fsdecode()should be used to ensure that the correct encoding and errors mode are used.- In the UTF-8 mode, the encoding is
utf-8on any platform. - On Mac OS X, the encoding is
'utf-8'. - On Unix, the encoding is the locale encoding.
- On Windows, the encoding may be
'utf-8'or'mbcs', depending on user configuration.
3.2 版更變:
getfilesystemencoding()result cannot beNoneanymore.3.6 版更變: Windows is no longer guaranteed to return
'mbcs'. See PEP 529 and_enablelegacywindowsfsencoding()for more information.3.7 版更變: Return 『utf-8』 in the UTF-8 mode.
- In the UTF-8 mode, the encoding is
-
sys.getfilesystemencodeerrors()¶ Return the name of the error mode used to convert between Unicode filenames and bytes filenames. The encoding name is returned from
getfilesystemencoding().os.fsencode()andos.fsdecode()should be used to ensure that the correct encoding and errors mode are used.3.6 版新加入.
-
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().
-
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
TypeErrorwill 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」; see
setswitchinterval().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,
ValueErroris 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.
-
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 accurate 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.
Availability: Windows.
3.2 版更變: Changed to a named tuple and added service_pack_minor, service_pack_major, suite_mask, and product_type.
3.6 版更變: Added platform_version
-
sys.get_asyncgen_hooks()¶ Returns an asyncgen_hooks object, which is similar to a
namedtupleof the form (firstiter, finalizer), where firstiter and finalizer are expected to be eitherNoneor functions which take an asynchronous generator iterator as an argument, and are used to schedule finalization of an asynchronous generator by an event loop.3.6 版新加入: See PEP 525 for more details.
備註
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 func:set_coroutine_origin_tracking_depth.
3.7 版新加入.
備註
This function has been added on a provisional basis (see PEP 411 for details.) Use it only for debugging purposes.
-
sys.get_coroutine_wrapper()¶ Returns
None, or a wrapper set byset_coroutine_wrapper().3.5 版新加入: See PEP 492 for more details.
備註
This function has been added on a provisional basis (see PEP 411 for details.) Use it only for debugging purposes.
3.7 版後已棄用: The coroutine wrapper functionality has been deprecated, and will be removed in 3.8. See bpo-32591 for details.
-
sys.hash_info¶ 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 widthwidth in bits used for hash values modulusprime modulus P used for numeric hash scheme infhash value returned for a positive infinity nanhash value returned for a nan imagmultiplier used for the imaginary part of a complex number algorithmname of the algorithm for hashing of str, bytes, and memoryview hash_bitsinternal output size of the hash algorithm seed_bitssize of the seed key of the hash algorithm 3.2 版新加入.
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.
