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 of
