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在使用标准configure
script, this contains the ABI flags as specified by PEP 3149.configure
脚本构建Python的POSIX系统上,它包含PEP 3149指定的ABI标志。Changed in version 3.8:版本3.8中更改:Default flags became an empty string (默认标志变为空字符串(pymalloc的m
flag for pymalloc has been removed).m
标志已删除)。New in version 3.2.版本3.2中新增。
-
sys.
addaudithook
(hook)¶ Append the callable hook to the list of active auditing hooks for the current (sub)interpreter.将可调用hook附加到当前(子)解释器的活动审核挂钩列表中。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.sys.audit()
函数引发审核事件时,将按照添加事件名称和参数元组的顺序调用每个挂钩。Native hooks added by首先调用PySys_AddAuditHook()
are called first, followed by hooks added in the current (sub)interpreter.PySys_AddAuditHook()
添加的本机挂钩,然后调用当前(子)解释器中添加的挂钩。Hooks can then log the event, raise an exception to abort the operation, or terminate the process entirely.然后,挂钩可以记录事件、引发异常以中止操作或完全终止进程。Calling调用sys.addaudithook()
will itself raise an auditing event namedsys.addaudithook
with no arguments.sys.addaudithook()
本身将引发一个名为sys.addaudithook
的审核事件,不带任何参数。If any existing hooks raise an exception derived from如果任何现有挂钩引发从RuntimeError
, the new hook will not be added and the exception suppressed.RuntimeError
派生的异常,则不会添加新挂钩并抑制异常。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.CPython提出的所有事件见审计事件表,原始设计讨论见PEP 578。New in version 3.8.版本3.8中新增。Changed in version 3.8.1:版本3.8.1中更改:Exceptions derived from从Exception
but notRuntimeError
are no longer suppressed.Exception
而非RuntimeError
派生的异常不再被抑制。CPython implementation detail:CPython实施详情: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.settrace()
),仅当可调用对象的__cantrace__
成员设置为真值时,才会跟踪Python挂钩。Otherwise, trace functions will skip the hook.否则,跟踪函数将跳过挂钩。
-
sys.
argv
¶ The list of command line arguments passed to a Python script.传递给Python脚本的命令行参数列表。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'
.-c
命令行选项执行的,则argv[0]
设置为字符串'-c'
。If no script name was passed to the Python interpreter,如果没有向Python解释器传递脚本名称,则argv[0]
is the empty string.argv[0]
是空字符串。To loop over the standard input, or the list of files given on the command line, see the要循环标准输入或命令行上给定的文件列表,请参阅fileinput
module.fileinput
模块。See also
sys.orig_argv
.Note
On Unix, command line arguments are passed by bytes from OS.在Unix上,命令行参数从操作系统按字节传递。Python decodes them with filesystem encoding and “surrogateescape” error handler.Python使用文件系统编码和“代理场景”错误处理程序对其进行解码。When you need original bytes, you can get it by当您需要原始字节时,可以通过[os.fsencode(arg) for arg in sys.argv]
.[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.event是标识事件的字符串,args可能包含可选参数,其中包含有关事件的更多信息。The number and types of arguments for a given event are considered a public and stable API and should not be modified between releases.给定事件的参数数量和类型被视为公共和稳定的API,不应在版本之间进行修改。For example, one auditing event is named例如,一个审核事件名为os.chdir
.os.chdir
。This event has one argument called path that will contain the requested new working directory.此事件有一个名为path的参数,该参数将包含请求的新工作目录。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.sys.addaudithook()
或PySys_AddAuditHook()
函数添加挂钩。The native equivalent of this function is此函数的本机等效项是PySys_Audit()
.PySys_Audit()
。Using the native function is preferred when possible.如果可能,最好使用本机函数。See the audit events table for all events raised by CPython.请参阅审核事件表了解CPython引发的所有事件。New in version 3.8.版本3.8中新增。
-
sys.
base_exec_prefix
¶ Set during Python startup, before在Python启动期间,在运行site.py
is run, to the same value asexec_prefix
.site.py
之前,将其设置为与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 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).site.py
发现虚拟环境正在使用中,prefix
和exec_prefix
的值将更改为指向虚拟环境,而base_prefix
和base_exec_prefix
将保持指向基本Python安装(创建虚拟环境的安装)。New in version 3.3.版本3.3中新增。
-
sys.
base_prefix
¶ Set during Python startup, before在Python启动期间,在运行site.py
is run, to the same value asprefix
.site.py
之前,将其设置为与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 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).site.py
发现虚拟环境正在使用中,prefix
和exec_prefix
的值将更改为指向虚拟环境,而base_prefix
和base_exec_prefix
将保持指向基本Python安装(创建虚拟环境的安装)。New in version 3.3.版本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.'big'
,在小端(最低有效字节前置)平台上,该值为'little'
。
-
sys.
builtin_module_names
¶ A tuple of strings containing the names of all modules that are compiled into this Python interpreter.一个字符串元组,包含编译到此Python解释器中的所有模块的名称。(This information is not available in any other way —(此信息以任何其他方式都不可用:modules.keys()
only lists the imported modules.)modules.keys()
仅列出导入的模块。)See also the另请参阅sys.stdlib_module_names
list.sys.stdlib_module_names
列表。
-
sys.
call_tracing
(func, args)¶ Call启用跟踪时调用func(*args)
, while tracing is enabled.func(*args)
。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.包含Python解释器版权的字符串。
-
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请注意,traceback
module can build the call stack given such a frame.traceback
模块中的函数可以在给定这种帧的情况下构建调用堆栈。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_frames
不带参数。
-
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.sys._current_exceptions
不带参数。
-
sys.
breakpointhook
()¶ This hook function is called by built-in此挂钩函数由内置breakpoint()
.breakpoint()
调用。By default, it drops you into the默认情况下,它会将您放入pdb
debugger, but it can be set to any other function so that you can choose which debugger gets used.pdb
调试器,但可以将其设置为任何其他函数,以便您可以选择使用哪个调试器。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).pdb.set_trace()
)不需要任何参数,但您可以将其绑定到需要其他参数(位置和/或关键字)的函数。The built-in内置breakpoint()
function passes its*args
and**kws
straight through.breakpoint()
函数直接传递其*args
和**kws
。Whateverbreakpointhooks()
returns is returned frombreakpoint()
.breakpointhooks()
返回的任何内容都是从breakpoint()
返回的。The default implementation first consults the environment variable默认实现首先参考环境变量PYTHONBREAKPOINT
.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."0"
,则此函数立即返回;例如,它是一个no-op。如果环境变量未设置,或设置为空字符串,则调用pd.bset_trace()
。Otherwise this variable should name a function to run, using Python’s dotted-import nomenclature, e.g.否则,该变量应使用Python的虚线导入命名法命名要运行的函数,例如package.subpackage.module.function
.package.subpackage.module.function
。In this case,在这种情况下,将导入package.subpackage.module
would be imported and the resulting module must have a callable namedfunction()
.package.subpackage.module
,生成的模块必须具有可调用的命名function()
。This is run, passing in这将运行,传入*args
and**kws
, and whateverfunction()
returns,sys.breakpointhook()
returns to the built-inbreakpoint()
function.*args
和**kws
,无论function()
返回什么,sys.breakpointhook()
都将返回到内置的breakpoint()
函数。Note that if anything goes wrong while importing the callable named by请注意,如果在导入由PYTHONBREAKPOINT
, aRuntimeWarning
is reported and the breakpoint is ignored.PYTHONBREAKPOINT
命名的可调用项时出现任何错误,将报告RuntimeWarning
,并忽略断点。Also note that if还请注意,如果以编程方式重写sys.breakpointhook()
is overridden programmatically,PYTHONBREAKPOINT
is not consulted.sys.breakpointhook()
,则不会参考PYTHONBREAKPOINT
。New in version 3.7.版本3.7中新增。
-
sys.
_debugmallocstats
()¶ Print low-level information to stderr about the state of CPython’s memory allocator.向stderr打印关于CPython内存分配器状态的低级信息。If Python is built in debug mode <debug-build> (如果Python是在调试模式<debug-build>下构建的(configure --with-pydebug option
), it also performs some expensive internal consistency checks.configure --with-pydebug option
),那么它也会执行一些昂贵的内部一致性检查。New in version 3.3.版本3.3中新增。CPython implementation detail:CPython实施详情:This function is specific to CPython. The exact output format is not defined here, and may change.此函数特定于CPython。此处未定义确切的输出格式,可能会更改。
-
sys.
dllhandle
¶ Integer specifying the handle of the Python DLL.指定Python DLL句柄的整数。Availability: Windows.
-
sys.
displayhook
(value)¶ If value is not如果value不是None
, this function printsrepr(value)
tosys.stdout
, and saves value inbuiltins._
.None
,则此函数将repr(value)
打印到sys.stdout
,并将value保存在builtins._
中。If如果repr(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.repr(value)
不能用sys.stdout.errors
错误处理程序编码为sys.stdout.encoding
(这可能是'strict'
),请用'backslashreplace'
错误处理程序将其编码为sys.stdout.encoding
。对交互式Python会话中输入的表达式求值的结果调用sys.displayhook
is called on the result of evaluating an expression entered in an interactive Python session.sys.displayhook
。The display of these values can be customized by assigning another one-argument function to可以通过向sys.displayhook
.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._ = valueChanged in version 3.2:版本3.2中更改:Use对'backslashreplace'
error handler onUnicodeEncodeError
.UnicodeEncodeError
使用'backslashreplace'
错误处理程序。
-
sys.
dont_write_bytecode
¶ If this is true, Python won’t try to write如果这是真的,Python将不会尝试在导入源模块时编写.pyc
files on the import of source modules..pyc
文件。This value is initially set to该值最初设置为True
orFalse
depending on the-B
command line option and thePYTHONDONTWRITEBYTECODE
environment variable, but you can set it yourself to control bytecode file generation.True
或False
,具体取决于-B
命令行选项和PYTHONDONTWRITEBYTECODE
环境变量,但您可以自行设置以控制字节码文件的生成。
-
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.None
),Python将把字节码缓存.pyc
文件写入(并从中读取)以该目录为根的并行目录树,而不是从源代码树中的__pycache__
目录。Any将忽略源代码树中的任何__pycache__
directories in the source code tree will be ignored and new .pyc files written within the pycache prefix.__pycache__
目录,并在pycache前缀中写入新的.pyc
文件。Thus if you use因此,如果将compileall
as a pre-build step, you must ensure you run it with the same pycache prefix (if any) that you will use at runtime.compileall
用作预构建步骤,则必须确保使用运行时使用的相同pycache前缀(如果有)运行它。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).-X
pycache_prefix=PATH
命令行选项或PYTHONPYCACHEPREFIX
环境变量(命令行优先)的值设置的。If neither are set, it is如果两者都未设置,则为None
.None
。New in version 3.8.版本3.8中新增。
-
sys.
excepthook
(type, value, traceback)¶ This function prints out a given traceback and exception to此函数向sys.stderr
.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.sys.excepthook
:异常类、异常实例和回溯对象。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.在交互式会话中,这发生在控件返回提示之前;在Python程序中,这发生在程序退出之前。The handling of such top-level exceptions can be customized by assigning another three-argument function to可以通过向sys.excepthook
.sys.excepthook
分配另一个三参数函数来定制此类顶级异常的处理。Raise an auditing event当发生未捕获异常时,使用参数sys.excepthook
with argumentshook
,type
,value
,traceback
when an uncaught exception occurs.hook
、type
、value
和traceback
引发审核事件sys.excepthook
。If no hook has been set,如果没有设置挂勾,hook
may beNone
.hook
可以是None
。If any hook raises an exception derived from如果任何挂钩引发从RuntimeError
the call to the hook will be suppressed.RuntimeError
派生的异常,那么对挂钩的调用将被抑制。Otherwise, the audit hook exception will be reported as unraisable and否则,审计挂钩异常将报告为不可访问,并将调用sys.excepthook
will be called.sys.excepthook
。See also
Thesys.unraisablehook()
function handles unraisable exceptions and thethreading.excepthook()
function handles exception raised bythreading.Thread.run()
.sys.unraisablehook()
函数处理不可验证的异常,threading.excepthook()
函数处理threading.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.breakpointhook
、displayhook
、excepthook
和unraisablehook
的原始值。They are saved so that它们被保存,以便在被损坏或替换的对象替换时,可以恢复breakpointhook
,displayhook
andexcepthook
,unraisablehook
can be restored in case they happen to get replaced with broken or alternative objects.breakpointhook
、displayhook
和excepthook
、unraisablehook
。New in version 3.7.版本3.7中新增。__breakpointhook__
New in version 3.8.版本3.8中新增。__unraisablehook__
-
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.这里,“处理异常”定义为“执行exception子句”对于任何堆栈帧,只能访问有关当前正在处理的异常的信息。If no exception is being handled anywhere on the stack, a tuple containing three如果堆栈上的任何位置都没有处理异常,则返回一个包含三个None
values is returned.None
值的元组。Otherwise, the values returned are否则,返回的值为(type, value, traceback)
.(type, value, traceback)
。Their meaning is: type gets the type of the exception being handled (a subclass of其含义是:type获取正在处理的异常的类型(BaseException
); value gets the exception instance (an instance of the exception type); traceback gets a traceback object which encapsulates the call stack at the point where the exception originally occurred.BaseException
的子类);value获取异常实例(异常类型的实例);traceback获取一个回溯对象,该对象在异常最初发生的位置封装调用堆栈。
-
sys.
exec_prefix
¶ A string giving the site-specific directory prefix where the platform-dependent Python files are installed; by default, this is also一个字符串,给出安装平台相关Python文件的特定于站点的目录前缀;默认情况下,这也是'/usr/local'
.'/usr/local'
。This can be set at build time with the这可以在构建时使用configure脚本的--exec-prefix
argument to the configure script.--exec-prefix
参数进行设置。Specifically, all configuration files (e.g. the具体来说,所有配置文件(例如pyconfig.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
.pyconfig.h
头文件)都安装在exec_prefix/lib/pythonX.Y/config
目录中,共享库模块安装在exec_prefix/lib/pythonX.Y/lib-dynload
目录中,其中X.Y是Python的版本号,例如3.2
。Note
If a virtual environment is in effect, this value will be changed in如果虚拟环境生效,则此值将在site.py
to point to the virtual environment.site.py
中更改为指向虚拟环境。The value for the Python installation will still be available, viaPython安装的值仍然可以通过base_exec_prefix
.base_exec_prefix
使用。
-
sys.
executable
¶ A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense.在有意义的系统上,为Python解释器提供可执行二进制文件的绝对路径的字符串。If Python is unable to retrieve the real path to its executable,如果Python无法检索其可执行文件的实际路径,sys.executable
will be an empty string orNone
.sys.executable
将是空字符串或None
。
-
sys.
exit
([arg])¶ Raise a引发SystemExit
exception, signaling an intention to exit the interpreter.SystemExit
异常,表示打算退出解释器。The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object.可选参数arg可以是给出退出状态的整数(默认为零),也可以是其他类型的对象。If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.如果是整数,则零被视为“成功终止”,任何非零值被shell等视为“异常终止”。Most systems require it to be in the range 0–127, and produce undefined results otherwise.大多数系统要求它在0-127范围内,否则会产生未定义的结果。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.一些系统有一个为特定退出代码指定特定含义的惯例,但这些系统通常还不发达;Unix程序通常使用2表示命令行语法错误,1表示所有其他类型的错误。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.None
等同于传递零,任何其他对象都会打印到stderr
,并导致退出代码为1。In particular,特别是,sys.exit("some error message")
is a quick way to exit a program when an error occurs.sys.exit("some error message")
是在发生错误时退出程序的一种快速方法。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.exit()
最终“仅”引发异常,因此它只会在从主线程调用时退出进程,并且不会截获该异常。Cleanup actions specified by finally clauses of遵循try
statements are honored, and it is possible to intercept the exit attempt at an outer level.try
语句的finally
子句指定的清理操作,并且可以在外部级别拦截退出尝试。Changed in version 3.6:版本3.6中更改:If an error occurs in the cleanup after the Python interpreter has caught如果Python解释器捕获到SystemExit
(such as an error flushing buffered data in the standard streams), the exit status is changed to 120.SystemExit
后在清理过程中发生错误(例如刷新标准流中的缓冲数据时出错),则退出状态将更改为120。
-
sys.
flags
¶ The named tuple flags exposes the status of command line flags.命名元组flags公开命令行标志的状态。The attributes are read only.属性为只读。attribute属性flag
debug
interactive
isolated
optimize
no_user_site
no_site
ignore_environment
verbose
bytes_warning
quiet
hash_randomization
dev_mode
utf8_mode
New in version 3.2.3.版本3.2.3中新增。Thehash_randomization
attribute.hash_randomization
属性。Changed in version 3.3:版本3.3中更改:Removed obsolete已删除过时的division_warning
attribute.division_warning
属性。Changed in version 3.4:版本3.4中更改:Added为isolated
attribute for-I
isolated
flag.-I
隔离标志添加了isolated
属性。Changed in version 3.7:版本3.7中更改:Added the为新的Python开发模式添加了dev_mode
attribute for the new Python Development Mode and theutf8_mode
attribute for the new-X
utf8
flag.dev_mode
属性,为新的-X
utf8
标志添加了utf8_mode
属性。
-
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这些值对应于“C”编程语言的标准头文件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.float.h
中定义的各种浮点常量;有关详细信息,请参阅1999年ISO/IEC C标准[C99]第5.2.4.2.2节,“浮动类型的特性”。attribute属性float.h
macro宏explanation解释epsilon
DBL_EPSILON
difference between 1.0 and the least value greater than 1.0 that is representable as a float1.0与可表示为浮点的大于1.0的最小值之间的差值See also另请参见math.ulp()
.math.ulp()
。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 floatradix
位数DBL_MAX
maximum representable positive finite float最大可表示正有限浮点数max_exp
DBL_MAX_EXP
maximum integer e such that最大整数e,使得radix**(e-1)
is a representable finite floatradix**(e-1)
是可表示的有限浮点max_10_exp
DBL_MAX_10_EXP
maximum integer e such that最大整数e,使得10**e
is in the range of representable finite floats10**e
在可表示的有限浮点范围内DBL_MIN
minimum representable positive normalized float最小可表示正归一化浮点Use使用math.ulp(0.0)
to get the smallest positive denormalized representable float.math.ulp(0.0)
获得最小的正非规范化可表示浮点。min_exp
DBL_MIN_EXP
minimum integer e such that最小整数e,使得radix**(e-1)
is a normalized floatradix**(e-1)
是标准化浮点min_10_exp
DBL_MIN_10_EXP
minimum integer e such that最小整数e,使得10**e
is a normalized float10**e
是标准化浮点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.这反映了解释器启动时系统FLT_ROUNDS宏的值。See section 5.2.4.2.2 of the C99 standard for an explanation of the possible values and their meanings.有关可能值及其含义的解释,请参阅C99标准第5.2.4.2.2节。The attributesys.float_info.dig
needs further explanation.sys.float_info.dig
属性需要进一步解释。If如果s
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:s
是表示十进制数的任何字符串,最多包含sys.float_info.dig
有效数字,则将s
转换为浮点并再次转换将恢复表示相同十进制值的字符串:>>> 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:sys.float_info.dig
有效数字的字符串,这并不总是正确的:>>> 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.repr()
函数对浮点的行为。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
.'short'
,那么对于有限浮点x
,repr(x)
旨在生成一个具有float(repr(x)) == x
属性的短字符串。This is the usual behaviour in Python 3.1 and later.这是Python 3.1及更高版本中的常见行为。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.float_repr_style
的值为'legacy'
,repr(x)
的行为方式与3.1之前的Python版本中的行为方式相同。New in version 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._clear_type_cache()
和gc.collect()
以获得更可预测的结果。If a Python build or implementation cannot reasonably compute this information,如果Python构建或实现无法合理计算此信息,则允许getallocatedblocks()
is allowed to return 0 instead.getallocatedblocks()
返回0。New in version 3.4.版本3.4中新增。
-
sys.
getandroidapilevel
()¶ Return the build time API version of Android as an integer.以整数形式返回Android的构建时API版本。Availability: Android.
New in version 3.7.版本3.7中新增。
-
sys.
getdefaultencoding
()¶ Return the name of the current default string encoding used by the Unicode implementation.返回Unicode实现使用的当前默认字符串编码的名称。
-
sys.
getdlopenflags
()¶ Return the current value of the flags that are used for返回用于dlopen()
calls.dlopen()
调用的标志的当前值。Symbolic names for the flag values can be found in the可以在os
module (RTLD_xxx
constants, e.g.os.RTLD_LAZY
).os
模块中找到标志值的符号名称(RTLD_xxx
常量,例如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.获取文件系统编码:文件系统错误处理程序用于在Unicode文件名和字节文件名之间转换的编码。The filesystem error handler is returned from文件系统错误处理程序是从getfilesystemencoding()
.getfilesystemencoding()
返回的。For best compatibility, str should be used for filenames in all cases, although representing filenames as bytes is also supported.为了获得最佳兼容性,尽管也支持将文件名表示为字节,但在所有情况下都应将str用于文件名。Functions accepting or returning filenames should support either str or bytes and internally convert to the system’s preferred representation.接受或返回文件名的函数应支持str或bytes,并在内部转换为系统的首选表示形式。os.fsencode()
and和os.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 thePyConfig_Read()
function: seefilesystem_encoding
andfilesystem_errors
members ofPyConfig
.PyConfig_Read()
函数在Python启动时配置文件系统编码和错误处理程序:请参阅PyConfig
的filesystem_encoding
和filesystem_errors
成员。Changed in version 3.2:版本3.2中更改:getfilesystemencoding()
result cannot be结果不能再为None
anymore.None
。Changed in version 3.6:版本3.6中更改:Windows is no longer guaranteed to returnWindows不再保证返回'mbcs'
.'mbcs'
。See PEP 529 and有关详细信息,请参阅PEP 529和_enablelegacywindowsfsencoding()
for more information._enablelegacywindowsfsencoding()
。Changed in version 3.7:版本3.7中更改:Return如果启用了Python UTF-8 Mode模式,则返回'utf-8'
if the Python UTF-8 Mode is enabled.'utf-8'
。
-
sys.
getfilesystemencodeerrors
()¶ Get the filesystem error handler: the error handler used with the filesystem encoding to convert between Unicode filenames and bytes filenames.获取文件系统错误处理程序:与文件系统编码一起使用的错误处理程序,用于在Unicode文件名和字节文件名之间进行转换。The filesystem encoding is returned from文件系统编码是从getfilesystemencoding()
.getfilesystemencoding()
返回的。os.fsencode()
and和os.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 thePyConfig_Read()
function: seefilesystem_encoding
andfilesystem_errors
members ofPyConfig
.PyConfig_Read()
函数在Python启动时配置文件系统编码和错误处理程序:请参阅PyConfig
的filesystem_encoding
和filesystem_errors
成员。New in version 3.6.版本3.6中新增。
-
sys.
getrefcount
(object)¶ Return the reference count of the object.返回object的引用计数。The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to返回的计数通常比您预期的要高,因为它包含(临时)引用作为getrefcount()
.getrefcount()
的参数。
-
sys.
getrecursionlimit
()¶ Return the current value of the recursion limit, the maximum depth of the Python interpreter stack.返回递归限制的当前值,即Python解释器堆栈的最大深度。This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.这个限制可以防止无限递归导致C堆栈溢出和Python崩溃。It can be set bysetrecursionlimit()
.
-
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.如果给定default,如果对象不提供检索大小的方法,将返回default。Otherwise a否则将引发TypeError
will be raised.TypeError
。getsizeof()
calls the object’s__sizeof__
method and adds an additional garbage collector overhead if the object is managed by the garbage collector.getsizeof()
调用对象的__sizeof__
方法,如果对象由垃圾收集器管理,则会添加额外的垃圾收集器开销。See recursive sizeof recipe for an example of using有关递归使用getsizeof()
recursively to find the size of containers and all their contents.getsizeof()
查找容器大小及其所有内容的示例,请参阅recursive sizeof recipe。
-
sys.
getswitchinterval
()¶ Return the interpreter’s “thread switch interval”; see返回解释器的“线程切换间隔”;请参阅setswitchinterval()
.setswitchinterval()
。New in version 3.2.版本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.如果给定了可选的整数depth,则返回堆栈顶部以下多次调用的帧对象。If that is deeper than the call stack,如果深度超过调用堆栈,则会引发ValueError
is raised.ValueError
。The default for depth is zero, returning the frame at the top of the call stack.depth的默认值为零,返回调用堆栈顶部的帧。Raises an auditing event引发审核事件sys._getframe
with no arguments.sys._getframe
没有参数。CPython implementation detail:CPython实施详情:This function should be used for internal and specialized purposes only.此功能只能用于内部和专用目的。It is not guaranteed to exist in all implementations of Python.它不能保证存在于所有Python实现中。
-
sys.
getprofile
()¶ -
Get the profiler function as set by获取由setprofile()
.setprofile()
设置的探查器函数。
-
sys.
gettrace
()¶ -
Get the trace function as set by获取settrace()
.settrace()
设置的跟踪函数。CPython implementation detail:CPython实施详情:Thegettrace()
function is intended only for implementing debuggers, profilers, coverage tools and the like.gettrace()
函数仅用于实现调试器、探查器、覆盖率工具等。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.它的行为是实现平台的一部分,而不是语言定义的一部分,因此可能无法在所有Python实现中使用。
-
sys.
getwindowsversion
()¶ Return a named tuple describing the Windows version currently running.返回描述当前运行的Windows版本的命名元组。The named elements are major, minor, build, platform, service_pack, service_pack_minor, service_pack_major, suite_mask, product_type and platform_version.命名元素包括major、minor、build、platform、service_pack、service_pack_minor、service_pack_major、suite_mask、product_type和platform_version。service_pack contains a string, platform_version a 3-tuple and all other values are integers.service_pack包含字符串、platform_version3元组,所有其他值都是整数。The components can also be accessed by name, so组件也可以通过名称进行访问,因此sys.getwindowsversion()[0]
is equivalent tosys.getwindowsversion().major
.sys.getwindowsversion()[0]
等效于sys.getwindowsversion().major
。For compatibility with prior versions, only the first 5 elements are retrievable by indexing.为了与以前的版本兼容,只有前5个元素可以通过索引检索。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此函数包装Win32GetVersionEx()
function; see the Microsoft documentation onOSVERSIONINFOEX()
for more information about these fields.GetVersionEx()
函数;有关这些字段的详细信息,请参阅OSVERSIONINFOEX()
上的Microsoft文档。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.从kernel32.dll派生版本,该版本可能与操作系统版本不同。Please use请使用platform
module for achieving accurate OS version.platform
模块实现准确的操作系统版本。Availability: Windows.
Changed in version 3.2:版本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:版本3.6中更改:Added platform_version添加了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.New in version 3.6.版本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()
.New in version 3.7.版本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.有关数字类型哈希的更多详细信息,请参阅数字类型哈希。attribute
explanation
width
width in bits used for hash values用于哈希值的宽度(位)modulus
prime modulus P used for numeric hash scheme用于数字哈希方案的素数模Pinf
hash value returned for a positive infinity为正无穷大返回的哈希值nan
(this attribute is no longer used)(不再使用此属性)imag
multiplier used for the imaginary part of a complex number用于复数虚部的乘法器algorithm
name of the algorithm for hashing of str, bytes, and memoryviewstr、bytes和memoryview哈希算法的名称hash_bits
internal output size of the hash algorithm哈希算法的内部输出大小seed_bits
size of the seed key of the hash algorithm哈希算法种子密钥的大小New in version 3.2.版本3.2中新增。Changed in version 3.4:版本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:例如,要测试Python解释器是否至少为1.5.2版,请使用: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.hexversion
,因为只有当将其作为传递给内置hex()
函数的结果时,它才看起来真正有意义。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.hexversion
的更多详细信息,请访问API和ABI版本控制。
-
sys.
implementation
¶ An object containing information about the implementation of the currently running Python interpreter.一个对象,包含有关当前运行的Python解释器实现的信息。The following attributes are required to exist in all Python implementations.所有Python实现中都需要以下属性。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.实际字符串由Python实现定义,但保证为小写。version is a named tuple, in the same format as
sys.version_info
.It represents the version of the Python implementation.它表示Python实现的版本。This has a distinct meaning from the specific version of the Python language to which the currently running interpreter conforms, which这与当前运行的解释器所遵循的Python语言的特定版本有着不同的含义,sys.version_info
represents.sys.version_info
表示了该版本。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.对于CPython,它们的值相同,因为它是参考实现。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'
.'cpython-33'
。However, a Python implementation may use some other value if appropriate.然而,如果合适的话,Python实现可以使用其他一些值。If如果cache_tag
is set toNone
, it indicates that module caching should be disabled.cache_tag
设置为None
,则表示应该禁用模块缓存。sys.implementation
may contain additional attributes specific to the Python implementation.可能包含特定于Python实现的其他属性。These non-standard attributes must start with an underscore, and are not described here.这些非标准属性必须以下划线开头,此处不作描述。Regardless of its contents,sys.implementation
will not change during a run of the interpreter, nor between implementation versions. (It may change between Python language versions, however.) See PEP 421 for more information.New in version 3.3.版本3.3中新增。
-
sys.
int_info
¶ A named tuple that holds information about Python’s internal representation of integers.一个命名元组,保存Python内部整数表示的信息。The attributes are read only.属性为只读。Attribute
Explanation
bits_per_digit
number of bits held in each digit.每个数字中保留的位数。Python integers are stored internally in basePython整数内部存储在基2**int_info.bits_per_digit
2**int_info.bits_per_digit
中sizeof_digit
size in bytes of the C type used to represent a digit用于表示数字的C类型的大小(字节)New in version 3.1.版本3.1中新增。
-
sys.
__interactivehook__
¶ When this attribute exists, its value is automatically called (with no arguments) when the interpreter is launched in interactive mode.当此属性存在时,当解释器以交互模式启动时,会自动调用其值(无参数)。This is done after thePYTHONSTARTUP
file is read, so that you can set this hook there.Thesite
module sets this.site
模块对此进行设置。Raises an auditing event在启动时调用挂钩时,引发审核事件cpython.run_interactivehook
with the hook object as the argument when the hook is called on startup.cpython.run_interactivehook
,挂钩对象作为参数。New in version 3.4.版本3.4中新增。
-
sys.
intern
(string)¶ Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy.在“interned”字符串表中输入string并返回interned字符串——即string本身或副本。Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare.保留字符串有助于提高字典查找的性能-如果字典中的键被保留,并且查找键被保留,则可以通过指针比较而不是字符串比较来进行键比较(哈希后)。Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.通常,Python程序中使用的名称是自动插入的,用于保存模块、类或实例属性的字典具有插入键。Interned strings are not immortal; you must keep a reference to the return value of插入的字符串不是不朽的;必须保留对intern()
around to benefit from it.intern()
返回值的引用,才能从中受益。
-
sys.
is_finalizing
()¶ Return如果Python解释器正在关闭,则返回True
if the Python interpreter is shutting down,False
otherwise.True
,否则返回False
。New in version 3.5.版本3.5中新增。
-
sys.
last_type
¶ -
sys.
last_value
¶ -
sys.
last_traceback
¶ These three variables are not always defined; they are set when an exception is not handled and the interpreter prints an error message and a stack traceback.这三个变量并不总是定义的;它们是在未处理异常且解释器打印错误消息和堆栈回溯时设置的。Their intended use is to allow an interactive user to import a debugger module and engage in post-mortem debugging without having to re-execute the command that caused the error.它们的预期用途是允许交互式用户导入调试器模块并进行事后调试,而无需重新执行导致错误的命令。(Typical use isimport pdb; pdb.pm()
to enter the post-mortem debugger; seepdb
module for more information.)The meaning of the variables is the same as that of the return values from变量的含义与上述exc_info()
above.exc_info()
返回值的含义相同。
-
sys.
maxsize
¶ An integer giving the maximum value a variable of type一个整数,给出Py_ssize_t
can take.Py_ssize_t
类型的变量可以接受的最大值。It’s usually在32位平台上通常是2**31 - 1
on a 32-bit platform and2**63 - 1
on a 64-bit platform.2**31-1
,在64位平台上通常是2**63-1
。
-
sys.
maxunicode
¶ An integer giving the value of the largest Unicode code point, i.e.给出最大Unicode代码点值的整数,即1114111
(0x10FFFF
in hexadecimal).1114111
(十六进制中的0x10FFFF
)。Changed in version 3.3:版本3.3中更改: Before PEP 393,sys.maxunicode
used to be either0xFFFF
or0x10FFFF
, depending on the configuration option that specified whether Unicode characters were stored as UCS-2 or UCS-4.
-
sys.
meta_path
¶ A list of meta path finder objects that have their
find_spec()
methods called to see if one of the objects can find the module to be imported. Thefind_spec()
method is called with at least the absolute name of the module being imported. If the module to be imported is contained in a package, then the parent package’s__path__
attribute is passed in as a second argument. The method returns a module spec, orNone
if the module cannot be found.See also
importlib.abc.MetaPathFinder
The abstract base class defining the interface of finder objects on定义meta_path
.meta_path
上查找器对象接口的抽象基类。importlib.machinery.ModuleSpec
The concrete class which
find_spec()
should return instances of.
Changed in version 3.4:版本3.4中更改: Module specs were introduced in Python 3.4, by PEP 451. Earlier versions of Python looked for a method calledfind_module()
. This is still called as a fallback if ameta_path
entry doesn’t have afind_spec()
method.
-
sys.
modules
¶ This is a dictionary that maps module names to modules which have already been loaded.这是一个将模块名称映射到已加载模块的字典。This can be manipulated to force reloading of modules and other tricks.这可以被操纵来强制重新加载模块和其他技巧。However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail.然而,替换字典不一定会按预期工作,从字典中删除基本项可能会导致Python失败。If you want to iterate over this global dictionary always use如果要迭代此全局字典,请始终使用sys.modules.copy()
ortuple(sys.modules)
to avoid exceptions as its size may change during iteration as a side effect of code or activity in other threads.sys.modules.copy()
或tuple(sys.modules)
来避免异常,因为在迭代过程中,它的大小可能会发生变化,这是其他线程中的代码或活动的副作用。
-
sys.
orig_argv
¶ The list of the original command line arguments passed to the Python executable.传递给Python可执行文件的原始命令行参数列表。See also另请参见sys.argv
.sys.argv
。New in version 3.10.版本3.10中新增。
-
sys.
path
¶ -
A list of strings that specifies the search path for modules.指定模块搜索路径的字符串列表。Initialized from the environment variablePYTHONPATH
, plus an installation-dependent default.As initialized upon program startup, the first item of this list,当程序启动时初始化时,此列表的第一项code>path[0]是包含用于调用Python解释器的脚本的目录。path[0]
, is the directory containing the script that was used to invoke the Python interpreter.If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input),如果脚本目录不可用(例如,如果以交互方式调用解释器或从标准输入读取脚本),则code>path[0]是空字符串,它指示Python首先在当前目录中搜索模块。path[0]
is the empty string, which directs Python to search modules in the current directory first.Notice that the script directory is inserted before the entries inserted as a result of请注意,脚本目录是在作为PYTHONPATH
.PYTHONPATH
结果插入的条目之前插入的。A program is free to modify this list for its own purposes.程序可以出于自身目的自由修改此列表。Only strings and bytes should be added to只能将字符串和字节添加到sys.path
; all other data types are ignored during import.sys.path
;导入期间将忽略所有其他数据类型。
-
sys.
path_hooks
¶ A list of callables that take a path argument to try to create a finder for the path.使用path参数尝试为路径创建查找器的可调用项列表。If a finder can be created, it is to be returned by the callable, else raise如果可以创建查找程序,则该查找程序将由可调用程序返回,否则将引发ImportError
.ImportError
。Originally specified in PEP 302.
-
sys.
path_importer_cache
¶ A dictionary acting as a cache for finder objects.作为查找器对象缓存的字典。The keys are paths that have been passed to键是传递给sys.path_hooks
and the values are the finders that are found.sys.path_hooks
的路径,值是找到的查找器。If a path is a valid file system path but no finder is found on如果路径是有效的文件系统路径,但在ssys.path_hooks
thenNone
is stored.sys.path_hooks
上找不到查找器,则会存储None
。Originally specified in PEP 302.
Changed in version 3.3:版本3.3中更改:None
is stored instead ofimp.NullImporter
when no finder is found.
-
sys.
platform
¶ This string contains a platform identifier that can be used to append platform-specific components to该字符串包含一个平台标识符,可用于将特定于平台的组件附加到sys.path
, for instance.sys.path
。For Unix systems, except on Linux and AIX, this is the lowercased OS name as returned by
uname -s
with the first part of the version as returned byuname -r
appended, e.g.'sunos5'
or'freebsd8'
, at the time when Python was built.Unless you want to test for a specific system version, it is therefore recommended to use the following idiom:除非要测试特定的系统版本,否则建议使用以下习惯用法:if sys.platform.startswith('freebsd'):
# FreeBSD-specific code here...
elif sys.platform.startswith('linux'):
# Linux-specific code here...
elif sys.platform.startswith('aix'):
# AIX-specific code here...For other systems, the values are:对于其他系统,值为:System
platform
valueAIX
'aix'
Linux
'linux'
Windows
'win32'
Windows/Cygwin
'cygwin'
macOS
'darwin'
Changed in version 3.3:版本3.3中更改: On Linux,sys.platform
doesn’t contain the major version anymore. It is always'linux'
, instead of'linux2'
or'linux3'
.Since older Python versions include the version number, it is recommended to always use the由于较早的Python版本包含版本号,建议始终使用上面介绍的startswith
idiom presented above.startswith
习语。Changed in version 3.8:版本3.8中更改: On AIX,sys.platform
doesn’t contain the major version anymore. It is always'aix'
, instead of'aix5'
or'aix7'
.Since older Python versions include the version number, it is recommended to always use the由于较早的Python版本包含版本号,建议始终使用上面介绍的startswith
idiom presented above.startswith
习语。See also
os.name
has a coarser granularity.os.uname()
gives system-dependent version information.Theplatform
module provides detailed checks for the system’s identity.platform
模块提供系统标识的详细检查。
-
sys.
platlibdir
¶ Name of the platform-specific library directory.平台特定库目录的名称。It is used to build the path of standard library and the paths of installed extension modules.它用于构建标准库的路径和已安装扩展模块的路径。It is equal to
"lib"
on most platforms. On Fedora and SuSE, it is equal to"lib64"
on 64-bit platforms which gives the followingsys.path
paths (whereX.Y
is the Pythonmajor.minor
version):/usr/lib64/pythonX.Y/
: Standard library (likeos.py
of theos
module)/usr/lib64/pythonX.Y/lib-dynload/
: C extension modules of the standard library (like theerrno
module, the exact filename is platform specific)/usr/lib/pythonX.Y/site-packages/
(always uselib
, notsys.platlibdir
): Third-party modules/usr/lib64/pythonX.Y/site-packages/
: C extension modules of third-party packages
New in version 3.9.版本3.9中新增。
-
sys.
prefix
¶ A string giving the site-specific directory prefix where the platform independent Python files are installed; on Unix, the default is一个字符串,给出安装平台无关Python文件的特定于站点的目录前缀;在Unix上,默认值为'/usr/local'
.'/usr/local'
。This can be set at build time with the--prefix
argument to the configure script. See Installation paths for derived paths.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_prefix
.
-
sys.
ps1
¶ -
sys.
ps2
¶ -
Strings specifying the primary and secondary prompt of the interpreter.指定解释器的主提示和辅助提示的字符串。These are only defined if the interpreter is in interactive mode.仅当口译员处于交互模式时才定义这些。Their initial values in this case are在这种情况下,它们的初始值是'>>> '
and'... '
.'>>> '
和'... '
。If a non-string object is assigned to either variable, its如果将非字符串对象分配给任一变量,则每次解释器准备读取新的交互式命令时,都会重新计算其str()
is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt.str()
;这可用于实现动态提示。
-
sys.
setdlopenflags
(n)¶ Set the flags used by the interpreter for设置解释器用于dlopen()
calls, such as when the interpreter loads extension modules.dlopen()
调用的标志,例如解释器加载扩展模块时。Among other things, this will enable a lazy resolving of symbols when importing a module, if called as除其他事项外,如果称为sys.setdlopenflags(0)
.sys.setdlopenflags(0)
,这将允许在导入模块时延迟解析符号。To share symbols across extension modules, call assys.setdlopenflags(os.RTLD_GLOBAL)
. Symbolic names for the flag values can be found in theos
module (RTLD_xxx
constants, e.g.os.RTLD_LAZY
).Availability: Unix.
-
sys.
setprofile
(profilefunc)¶ -
Set the system’s profile function, which allows you to implement a Python source code profiler in Python.设置系统的profile函数,它允许您在Python中实现Python源代码探查器。See chapter The Python Profilers for more information on the Python profiler.有关Python探查器的更多信息,请参阅Python探查器一章。The system’s profile function is called similarly to the system’s trace function (see系统的概要文件函数的调用与系统的跟踪函数类似(请参见settrace()
), but it is called with different events, for example it isn’t called for each executed line of code (only on call and return, but the return event is reported even when an exception has been set).settrace()
),但它是通过不同的事件调用的,例如,它不是针对每一行执行的代码调用的(仅在调用和返回时调用,但即使设置了异常,也会报告返回事件)。The function is thread-specific, but there is no way for the profiler to know about context switches between threads, so it does not make sense to use this in the presence of multiple threads.该函数是特定于线程的,但探查器无法了解线程之间的上下文切换,因此在存在多个线程的情况下使用它是没有意义的。Also, its return value is not used, so it can simply return此外,它的返回值没有被使用,因此它可以简单地返回None
.None
。Error in the profile function will cause itself unset.配置文件函数中的错误将导致其自身未设置。Profile functions should have three arguments: frame, event, and arg. frame is the current stack frame. event is a string:
'call'
,'return'
,'c_call'
,'c_return'
, or'c_exception'
. arg depends on the event type.Raises an auditing event引发不带参数的审核事件sys.setprofile
with no arguments.sys.setprofile
。The events have the following meaning:这些事件具有以下含义:'call'
A function is called (or some other code block entered).调用函数(或输入其他代码块)。The profile function is called; arg isNone
.'return'
A function (or other code block) is about to return.函数(或其他代码块)即将返回。The profile function is called; arg is the value that will be returned, orNone
if the event is caused by an exception being raised.'c_call'
A C function is about to be called.即将调用C函数。This may be an extension function or a built-in.这可能是一个扩展函数或内置函数。arg is the C function object.'c_return'
A C function has returned.已返回C函数。arg is the C function object.arg是C函数对象。'c_exception'
A C function has raised an exception.C函数引发了异常。arg is the C function object.arg是C函数对象。
-
sys.
setrecursionlimit
(limit)¶ Set the maximum depth of the Python interpreter stack to limit.将Python解释器堆栈的最大深度设置为limit。This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.这个限制可以防止无限递归导致C堆栈溢出和Python崩溃。The highest possible limit is platform-dependent.最高可能限制取决于平台。A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit.当用户有需要深度递归的程序和支持更高限制的平台时,可能需要将限制设置得更高。This should be done with care, because a too-high limit can lead to a crash.应小心操作,因为过高的限制可能会导致崩溃。If the new limit is too low at the current recursion depth, a如果当前递归深度的新限制太低,将引发RecursionError
exception is raised.RecursionError
异常。Changed in version 3.5.1:版本3.5.1中更改:A如果当前递归深度的新限制过低,则会引发RecursionError
exception is now raised if the new limit is too low at the current recursion depth.RecursionError
异常。
-
sys.
setswitchinterval
(interval)¶ Set the interpreter’s thread switch interval (in seconds).设置解释器的线程切换间隔(秒)。This floating-point value determines the ideal duration of the “timeslices” allocated to concurrently running Python threads. Please note that the actual value can be higher, especially if long-running internal functions or methods are used.这个浮点值决定了分配给并发运行的Python线程的“时间片”的理想持续时间。请注意,实际值可能更高,特别是如果使用长期运行的内部函数或方法。Also, which thread becomes scheduled at the end of the interval is the operating system’s decision.此外,在间隔结束时调度哪个线程是操作系统的决定。The interpreter doesn’t have its own scheduler.解释器没有自己的调度器。New in version 3.2.版本3.2中新增。
-
sys.
settrace
(tracefunc)¶ -
Set the system’s trace function, which allows you to implement a Python source code debugger in Python.设置系统的跟踪函数,该函数允许您在Python中实现Python源代码调试器。The function is thread-specific; for a debugger to support multiple threads, it must register a trace function using该函数是特定于线程的;为了使调试器支持多个线程,它必须为正在调试的每个线程使用settrace()
for each thread being debugged or usethreading.settrace()
.settrace()
注册跟踪函数,或者使用threading.settrace()
。Trace functions should have three arguments: frame, event, and arg. frame is the current stack frame. event is a string:
'call'
,'line'
,'return'
,'exception'
or'opcode'
. arg depends on the event type.The trace function is invoked (with event set to
'call'
) whenever a new local scope is entered; it should return a reference to a local trace function to be used for the new scope, orNone
if the scope shouldn’t be traced.The local trace function should return a reference to itself (or to another function for further tracing in that scope), or本地跟踪函数应返回对自身的引用(或对另一个函数的引用,以便在该范围内进行进一步跟踪),或返回None
to turn off tracing in that scope.None
以关闭该范围内的跟踪。If there is any error occurred in the trace function, it will be unset, just like如果跟踪函数中出现任何错误,它将被取消设置,就像调用settrace(None)
is called.settrace(None)
一样。The events have the following meaning:这些事件具有以下含义:'call'
A function is called (or some other code block entered).调用函数(或输入其他代码块)。The global trace function is called; arg is调用全局跟踪函数;arg为None
; the return value specifies the local trace function.None
;返回值指定本地跟踪函数。'line'
The interpreter is about to execute a new line of code or re-execute the condition of a loop.解释器即将执行一行新代码或重新执行循环的条件。The local trace function is called; arg is调用本地跟踪函数;arg为None
; the return value specifies the new local trace function.None
;返回值指定新的本地跟踪函数。SeeObjects/lnotab_notes.txt
for a detailed explanation of how this works. Per-line events may be disabled for a frame by settingf_trace_lines
toFalse
on that frame.'return'
A function (or other code block) is about to return.函数(或其他代码块)即将返回。The local trace function is called; arg is the value that will be returned, or调用本地跟踪函数;arg是将返回的值,如果引发异常导致事件,则返回None
if the event is caused by an exception being raised.None
。The trace function’s return value is ignored.'exception'
An exception has occurred.发生异常。The local trace function is called; arg is a tuple(exception, value, traceback)
; the return value specifies the new local trace function.'opcode'
The interpreter is about to execute a new opcode (see解释器即将执行一个新的操作码(有关操作码的详细信息,请参阅dis
for opcode details).dis
)。The local trace function is called; arg is调用本地跟踪函数;arg为None
; the return value specifies the new local trace function.None
;返回值指定新的本地跟踪函数。Per-opcode events are not emitted by default: they must be explicitly requested by settingf_trace_opcodes
toTrue
on the frame.
Note that as an exception is propagated down the chain of callers, an请注意,当异常沿着调用方链传播时,将在每个级别生成'exception'
event is generated at each level.'exception'
事件。For more fine-grained usage, it’s possible to set a trace function by assigning
frame.f_trace = tracefunc
explicitly, rather than relying on it being set indirectly via the return value from an already installed trace function.This is also required for activating the trace function on the current frame, which这也是激活当前帧上的跟踪函数所必需的,而settrace()
doesn’t do.settrace()
不需要这样做。Note that in order for this to work, a global tracing function must have been installed with请注意,为了使其正常工作,必须与settrace()
in order to enable the runtime tracing machinery, but it doesn’t need to be the same tracing function (e.g. it could be a low overhead tracing function that simply returnsNone
to disable itself immediately on each frame).settrace()
一起安装全局跟踪函数才能启用运行时跟踪机制,但它不需要是相同的跟踪函数(例如,它可以是一个低开销的跟踪函数,只需返回None
即可在每一帧上立即禁用自身)。For more information on code and frame objects, refer to The standard type hierarchy.有关代码和框架对象的详细信息,请参阅标准类型层次结构。Raises an auditing event引发不带参数的审核事件sys.settrace
with no arguments.sys.settrace
。CPython implementation detail:CPython实施详情:Thesettrace()
function is intended only for implementing debuggers, profilers, coverage tools and the like.settrace()
函数仅用于实现调试器、探查器、覆盖率工具等。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.它的行为是实现平台的一部分,而不是语言定义的一部分,因此可能无法在所有Python实现中使用。Changed in version 3.7:版本3.7中更改:'opcode'
event type added;f_trace_lines
andf_trace_opcodes
attributes added to frames
-
sys.
set_asyncgen_hooks
(firstiter, finalizer)¶ Accepts two optional keyword arguments which are callables that accept an asynchronous generator iterator as an argument.接受两个可选关键字参数,它们是可调用的,接受异步生成器迭代器作为参数。The firstiter callable will be called when an asynchronous generator is iterated for the first time.第一次迭代异步生成器时,将调用firstiter可回调对象。The finalizer will be called when an asynchronous generator is about to be garbage collected.当异步生成器即将被垃圾收集时,将调用终结器。Raises an auditing event引发审核事件sys.set_asyncgen_hooks_firstiter
with no arguments.sys.set_asyncgen_hooks_firstiter
,不带参数。Raises an auditing event引发审核事件sys.set_asyncgen_hooks_finalizer
with no arguments.sys.set_asyncgen_hooks_finalizer
,不带参数。Two auditing events are raised because the underlying API consists of two calls, each of which must raise its own event.引发两个审核事件,因为基础API由两个调用组成,每个调用都必须引发自己的事件。New in version 3.6.版本3.6中新增。See PEP 525 for more details, and for a reference example of a finalizer method see the implementation ofasyncio.Loop.shutdown_asyncgens
in Lib/asyncio/base_events.py
-
sys.
set_coroutine_origin_tracking_depth
(depth)¶ Allows enabling or disabling coroutine origin tracking.允许启用或禁用协同路由原点跟踪。When enabled, the启用后,协同路由对象上的cr_origin
attribute on coroutine objects will contain a tuple of (filename, line number, function name) tuples describing the traceback where the coroutine object was created, with the most recent call first. When disabled,cr_origin
will be None.cr_origin
属性将包含一个元组(文件名、行号、函数名),该元组描述了创建协同路由对象的回溯位置,其中最新的调用位于第一位。禁用时,cr_origin
将为None
。To enable, pass a depth value greater than zero; this sets the number of frames whose information will be captured.要启用,请传递大于零的depth值;这将设置将捕获其信息的帧数。To disable, pass set depth to zero.若要禁用,请将设置depth传递为零。This setting is thread-specific.
New in version 3.7.版本3.7中新增。
-
sys.
_enablelegacywindowsfsencoding
()¶ Changes the filesystem encoding and error handler to ‘mbcs’ and ‘replace’ respectively, for consistency with versions of Python prior to 3.6.将文件系统编码和错误处理程序分别更改为“mbcs”和“replace”,以与3.6之前的Python版本保持一致。This is equivalent to defining the
PYTHONLEGACYWINDOWSFSENCODING
environment variable before launching Python.See also
sys.getfilesystemencoding()
andsys.getfilesystemencodeerrors()
.Availability: Windows.
New in version 3.6.版本3.6中新增。See PEP 529 for more details.
-
sys.
stdin
¶ -
sys.
stdout
¶ -
sys.
stderr
¶ File objects文件对象used by the interpreter for standard input, output and errors:解释器用于标准输入、输出和错误:stdin
is used for all interactive input (including calls to用于所有交互式输入(包括对input()
);input()
的调用);stdout
is used for the output ofprint()
and expression statements and for the prompts ofinput()
;The interpreter’s own prompts and its error messages go to解释器自己的提示及其错误消息将转到stderr
.stderr
。
These streams are regular text files like those returned by the这些流是常规文本文件,类似于open()
function.open()
函数返回的文本文件。Their parameters are chosen as follows:其参数选择如下:The encoding and error handling are is initialized from
PyConfig.stdio_encoding
andPyConfig.stdio_errors
.On Windows, UTF-8 is used for the console device.在Windows上,UTF-8用于控制台设备。Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage).非字符设备(如磁盘文件和管道)使用系统区域设置编码(即ANSI代码页)。Non-console character devices such as NUL (i.e. whereisatty()
returnsTrue
) use the value of the console input and output codepages at startup, respectively for stdin and stdout/stderr.This defaults to the system locale encoding if the process is not initially attached to a console.如果进程最初未连接到控制台,则默认为系统区域设置编码。The special behaviour of the console can be overridden by setting the environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python.在启动Python之前,可以通过设置环境变量PYTHONLEGACYWINDOWSSTDIO来覆盖控制台的特殊行为。In that case, the console codepages are used as for any other character device.在这种情况下,控制台代码页与任何其他字符设备一样使用。Under all platforms, you can override the character encoding by setting the
PYTHONIOENCODING
environment variable before starting Python or by using the new-X
utf8
command line option andPYTHONUTF8
environment variable. However, for the Windows console, this only applies whenPYTHONLEGACYWINDOWSSTDIO
is also set.When interactive, the交互时,stdout
stream is line-buffered. Otherwise, it is block-buffered like regular text files.stdout
流是行缓冲的。否则,它会像普通文本文件一样进行块缓冲。Thestderr
stream is line-buffered in both cases. You can make both streams unbuffered by passing the-u
command-line option or setting thePYTHONUNBUFFERED
environment variable.
Changed in version 3.9:版本3.9中更改: Non-interactivestderr
is now line-buffered instead of fully buffered.Note
To write or read binary data from/to the standard streams, use the underlying binary要在标准流中写入或读取二进制数据,请使用底层二进制buffer
object.buffer
对象。For example, to write bytes tostdout
, usesys.stdout.buffer.write(b'abc')
.However, if you are writing a library (and do not control in which context its code will be executed), be aware that the standard streams may be replaced with file-like objects like但是,如果您正在编写库(并且不控制其代码将在哪个上下文中执行),请注意,标准流可能会替换为类似文件的对象,例如不支持io.StringIO
which do not support thebuffer
attribute.buffer
属性的io.StringIO
。
-
sys.
__stdin__
¶ -
sys.
__stdout__
¶ -
sys.
__stderr__
¶ These objects contain the original values of这些对象包含程序开始时的stdin
,stderr
andstdout
at the start of the program.stdin
、stderr
和stdout
的原始值。They are used during finalization, and could be useful to print to the actual standard stream no matter if the它们在最终确定期间使用,无论sys.std*
object has been redirected.sys.std*
对象是否已重定向,都可以用于打印到实际的标准流。It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object.它还可以用于将实际文件还原为已知的工作文件对象,以防它们被损坏的对象覆盖。However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.但是,执行此操作的首选方法是在替换之前显式保存以前的流,并还原保存的对象。Note
Under some conditions
stdin
,stdout
andstderr
as well as the original values__stdin__
,__stdout__
and__stderr__
can beNone
. It is usually the case for Windows GUI apps that aren’t connected to a console and Python apps started with pythonw.
-
sys.
stdlib_module_names
¶ A frozenset of strings containing the names of standard library modules.包含标准库模块名称的冻结字符串集。It is the same on all platforms. Modules which are not available on some platforms and modules disabled at Python build are also listed.在所有平台上都是一样的。还列出了在某些平台上不可用的模块和在Python构建时禁用的模块。All module kinds are listed: pure Python, built-in, frozen and extension modules.列出了所有类型的模块:纯Python、内置、冻结和扩展模块。Test modules are excluded.不包括测试模块。For packages, only the main package is listed: sub-packages and sub-modules are not listed.对于包,仅列出主包:未列出子包和子模块。For example, theemail
package is listed, but theemail.mime
sub-package and theemail.message
sub-module are not listed.See also the另请参见sys.builtin_module_names
list.sys.builtin_module_names
列表。New in version 3.10.版本3.10中新增。
-
sys.
thread_info
¶ A named tuple holding information about the thread implementation.包含线程实现信息的命名元组。Attribute
Explanation
name
Name of the thread implementation:线程实现的名称:'nt'
: Windows threads'pthread'
: POSIX threads'solaris'
: Solaris threads
lock
Name of the lock implementation:锁实现的名称:'semaphore'
: a lock uses a semaphore'mutex+cond'
: a lock uses a mutex and a condition variableNone
if this information is unknown
Name and version of the thread library.线程库的名称和版本。It is a string, or它是一个字符串,如果此信息未知,则为None
if this information is unknown.None
。New in version 3.3.版本3.3中新增。
-
sys.
tracebacklimit
¶ When this variable is set to an integer value, it determines the maximum number of levels of traceback information printed when an unhandled exception occurs.当此变量设置为整数值时,它确定发生未处理异常时打印的回溯信息的最大级别数。The default is默认值为1000
.1000
。When set to设置为0
or less, all traceback information is suppressed and only the exception type and value are printed.0
或更小时,将抑制所有回溯信息,仅打印异常类型和值。
-
sys.
unraisablehook
(unraisable, /)¶ Handle an unraisable exception.
Called when an exception has occurred but there is no way for Python to handle it. For example, when a destructor raises an exception or during garbage collection (
gc.collect()
).The unraisable argument has the following attributes:unraisable参数具有以下属性:exc_type
: Exception type.:异常类型。exc_value
: Exception value, can be:异常值,可以为None
.NOne
。exc_traceback: Exception traceback, can be
None
.err_msg: Error message, can be
None
.object: Object causing the exception, can be
None
.
The default hook formats err_msg and object as:
f'{err_msg}: {object!r}'
; use “Exception ignored in” error message if err_msg isNone
.sys.unraisablehook()
can be overridden to control how unraisable exceptions are handled.可以重写以控制如何处理不可验证的异常。Storing exc_value using a custom hook can create a reference cycle.使用自定义挂钩存储exc_value可以创建引用循环。It should be cleared explicitly to break the reference cycle when the exception is no longer needed.当不再需要异常时,应明确清除它以中断引用循环。Storing object using a custom hook can resurrect it if it is set to an object which is being finalized.如果将object设置为正在最终确定的对象,则使用自定义挂钩存储对象可以恢复该对象。Avoid storing object after the custom hook completes to avoid resurrecting objects.避免在自定义挂钩完成后存储object,以避免恢复对象。See also另请参见处理未捕获异常的excepthook()
which handles uncaught exceptions.excepthook()
。Raise an auditing event
sys.unraisablehook
with argumentshook
,unraisable
when an exception that cannot be handled occurs. Theunraisable
object is the same as what will be passed to the hook. If no hook has been set,hook
may beNone
.New in version 3.8.版本3.8中新增。
-
sys.
version
¶ A string containing the version number of the Python interpreter plus additional information on the build number and compiler used.一个字符串,包含Python解释器的版本号,以及有关内部版本号和所用编译器的其他信息。This string is displayed when the interactive interpreter is started.该字符串在交互式解释器启动时显示。Do not extract version information out of it, rather, useversion_info
and the functions provided by theplatform
module.
-
sys.
api_version
¶ The C API version for this interpreter.此解释器的C API版本。Programmers may find this useful when debugging version conflicts between Python and extension modules.当调试Python和扩展模块之间的版本冲突时,程序员可能会发现这很有用。
-
sys.
version_info
¶ A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is
'alpha'
,'beta'
,'candidate'
, or'final'
. Theversion_info
value corresponding to the Python version 2.0 is(2, 0, 0, 'final', 0)
. The components can also be accessed by name, sosys.version_info[0]
is equivalent tosys.version_info.major
and so on.Changed in version 3.1:版本3.1中更改:Added named component attributes.添加了命名组件属性。
-
sys.
warnoptions
¶ This is an implementation detail of the warnings framework; do not modify this value.这是警告框架的实现细节;请勿修改此值。Refer to the有关警告框架的更多信息,请参阅warnings
module for more information on the warnings framework.warnings
模块。
-
sys.
winver
¶ The version number used to form registry keys on Windows platforms.用于在Windows平台上形成注册表项的版本号。This is stored as string resource 1000 in the Python DLL.这将作为字符串资源1000存储在Python DLL中。The value is normally the first three characters of该值通常是version
.version
的前三个字符。It is provided in the在sys
module for informational purposes; modifying this value has no effect on the registry keys used by Python.sys
模块中提供,以供参考;修改此值对Python使用的注册表项没有影响。Availability: Windows.
-
sys.
_xoptions
¶ A dictionary of the various implementation-specific flags passed through the通过-X
command-line option.-X
命令行选项传递的各种实现特定标志的字典。Option names are either mapped to their values, if given explicitly, or to选项名称要么映射到它们的值(如果显式给定),要么映射到True
.True
。Example:例子:$ ./python -Xa=b -Xc
Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys._xoptions
{'a': 'b', 'c': True}CPython implementation detail:CPython实施详情:This is a CPython-specific way of accessing options passed through这是一种特定于CPython的访问通过-X
.-X
传递的选项的方法。Other implementations may export them through other means, or not at all.其他实现可以通过其他方式导出它们,也可以根本不导出。New in version 3.2.版本3.2中新增。
Citations
- C99
ISO/IEC 9899:1999. “Programming languages – C.” A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.