sys --- 系统相关的参数和函数¶
该模块提供了一些变量和函数。这些变量可能被解释器使用,也可能由解释器提供。这些函数会影响解释器。本模块总是可用的。
-
sys.abiflags¶ 在POSIX系统上,以标准的
configure脚本构建的 Python 中,这个变量会包含 PEP 3149 中定义的ABI标签。在 3.8 版更改: 默认的 flags 变为了空字符串(用于 pymalloc 的
m旗标已经移除)3.2 新版功能.
-
sys.addaudithook(hook)¶ 将可调用的 hook 附加到当前解释器的活动的审核钩子列表中。
通过
sys.audit()函数引发审计事件时,将按照加入钩子的先后顺序调用每个钩子,调用时将带有事件名称和参数元组。首先调用由PySys_AddAuditHook()添加的静态钩子,然后调用添加到当前解释器中的钩子。引发一个 审计事件
sys.addaudithook,没有附带参数。3.8 新版功能.
在 3.8.1 版更改: 派生自
Exception(而非RuntimeError)的异常不会被抑制。CPython implementation detail: 启用跟踪时(参阅
settrace()),仅当可调用对象(钩子)的__cantrace__成员设置为 true 时,才会跟踪该钩子。否则,跟踪功能将跳过该钩子。
-
sys.argv¶ 一个列表,其中包含了被传递给 Python 脚本的命令行参数。
argv[0]为脚本的名称(是否是完整的路径名取决于操作系统)。如果是通过 Python 解释器的命令行参数-c来执行的,argv[0]会被设置成字符串'-c'。如果没有脚本名被传递给 Python 解释器,argv[0]为空字符串。为了遍历标准输入,或者通过命令行传递的文件列表,参照
fileinput模块注解
在 Unix 上,系统传递的命令行参数是字节类型的。Python 使用文件系统编码和 "surrogateescape" 错误处理程序对它们进行解码。当需要原始字节时,可以通过
[os.fsencode(arg) for arg in sys.argv]来获取。
-
sys.audit(event, *args)¶ 利用某些活动的钩子引发审计事件。事件名称是一个字符串,用于标记事件及其关联的架构(即参数的数量和类型)。给定事件的架构应视作公开且稳定的 API,并且不应在版本之间进行修改。
任何钩子抛出第一个异常时,此函数也将抛出该异常。通常不应处理这些错误,而应尽快终止该进程。
钩子程序由
sys.addaudithook()或PySys_AddAuditHook()函数添加。与本函数相等效的原生函数是
PySys_Audit(),应尽量使用原生函数。参阅 审计事件表 以获取 CPython 定义的所有审计事件。
3.8 新版功能.
-
sys.base_exec_prefix¶ 在
site.py运行之前, Python 启动的时候被设置为跟exec_prefix同样的值。如果不是运行在 虚拟环境 中,两个值会保持相同;如果site.py发现处于一个虚拟环境中,prefix和exec_prefix将会指向虚拟环境。然而base_prefix和base_exec_prefix将仍然会指向基础的 Python 环境(用来创建虚拟环境的 Python 环境)3.3 新版功能.
-
sys.base_prefix¶ 在
site.py运行之前, Python 启动的时候被设置为跟prefix同样的值。如果不是运行在 虚拟环境 中, 两个值会保持相同;如果site.py发现处于一个虚拟环境中,prefix和exec_prefix将会指向虚拟环境。然而base_prefix和base_exec_prefix将仍然会指向基础的 Python 环境(用来创建虚拟环境的 Python 环境)3.3 新版功能.
-
sys.byteorder¶ 本地字节顺序的指示符。在大端序(最高有效位优先)操作系统上值为
'big',在小端序(最低有效位优先)操作系统上为'little'。
-
sys.builtin_module_names¶ 一个元素为字符串的元组。包含了所有的被编译进 Python 解释器的模块。(这个信息无法通过其他的办法获取,
modules.keys()只包括被导入过的模块。)
-
sys.call_tracing(func, args)¶ 在启用跟踪时调用
func(*args)来保存跟踪状态,然后恢复跟踪状态。这将从检查点的调试器调用,以便递归地调试其他的一些代码。
-
sys.copyright¶ 一个字符串,包含了 Python 解释器有关的版权信息
-
sys._clear_type_cache()¶ 清除内部的类型缓存。类型缓存是为了加速查找方法和属性的。在调试引用泄漏的时候调用这个函数 只会 清除不必要的引用。
这个函数应该只在内部为了一些特定的目的使用。
-
sys._current_frames()¶ 返回一个字典,存放着每个线程的标识符与(调用本函数时)该线程栈顶的帧(当前活动的帧)之间的映射。注意
traceback模块中的函数可以在给定某一帧的情况下构建调用堆栈。这对于调试死锁最有用:本函数不需要死锁线程的配合,并且只要这些线程的调用栈保持死锁,它们就是冻结的。在调用本代码来检查栈顶的帧的那一刻,非死锁线程返回的帧可能与该线程当前活动的帧没有任何关系。
这个函数应该只在内部为了一些特定的目的使用。
引发一个 审计事件
sys._current_frames,没有附带参数。
-
sys.breakpointhook()¶ 本钩子函数由内建函数
breakpoint()调用。默认情况下,它将进入pdb调试器,但可以将其改为任何其他函数,以选择使用哪个调试器。该函数的特征取决于其调用的函数。例如,默认绑定(即
pdb.set_trace())不要求提供参数,但可以将绑定换成要求提供附加参数(位置参数/关键字参数)的函数。内建函数breakpoint()直接将其*args和**kws传入。breakpointhooks()返回的所有内容都会从breakpoint()返回。默认的实现首先会查询环境变量
PYTHONBREAKPOINT。如果将该变量设置为"0",则本函数立即返回,表示在断点处无操作。如果未设置该环境变量或将其设置为空字符串,则调用pdb.set_trace()。否则,此变量应指定要运行的函数,指定函数时应使用 Python 的点导入命名法,如package.subpackage.module.function。这种情况下将导入package.subpackage.module,且导入的模块必须有一个名为function()的可调用对象。该可调用对象会运行,*args和**kws会传入,且无论function()返回什么,sys.breakpointhook()都将返回到內建函数breakpoint()。注意,如果在导入
PYTHONBREAKPOINT指定的可调用对象时出错,则将报告一个RuntimeWarning并忽略断点。另请注意,如果以编程方式覆盖
sys.breakpointhook(),则 不会 查询PYTHONBREAKPOINT。3.7 新版功能.
-
sys._debugmallocstats()¶ 将有关 CPython 内存分配器状态的底层的信息打印至 stderr。
如果 Python 被配置为 --with-pydebug,本方法还将执行一些开销较大的内部一致性检查。
3.3 新版功能.
CPython implementation detail: 本函数仅限 CPython。此处没有定义确切的输出格式,且可能会更改。
-
sys.displayhook(value)¶ 如果 value 不是
None,则本函数会将repr(value)打印至sys.stdout,并将 value 保存在builtins._中。如果repr(value)无法用sys.stdout.errors错误回调方法(可能较为“严格”)编码为sys.stdout.encoding,请用'backslashreplace'错误回调方法将其编码为sys.stdout.encoding。在交互式 Python 会话中运行 expression 产生结果后,将在结果上调用
sys.displayhook。若要自定义这些 value 的显示,可以将sys.displayhook指定为另一个单参数函数。伪代码:
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 版更改: 在发生
UnicodeEncodeError时使用'backslashreplace'错误回调方法。
-
sys.dont_write_bytecode¶ 如果该值为 true,则 Python 在导入源码模块时将不会尝试写入
.pyc文件。该值会被初始化为True或False,依据是-B命令行选项和PYTHONDONTWRITEBYTECODE环境变量,可以自行设置该值,来控制是否生成字节码文件。
-
sys.pycache_prefix¶ 如果将该选项设为某个目录(不是
None),Python 会将字节码缓存文件.pyc写入到以该目录为根的并行目录树中(并从中读取),而不是在源码树中的__pycache__目录下读写。源码树中所有的__pycache__目录都将被忽略,并将在 pycache prefix 内写入新的 .pyc 文件。因此,如果使用compileall作为预构建步骤,则必须确保预构建时使用的 pycache prefix (如果有)与将来运行的时候相同。相对路径将解释为相对于当前工作目录。
该值的初值设置,依据
-Xpycache_prefix=PATH命令行选项或PYTHONPYCACHEPREFIX环境变量的值(命令行优先)。如果两者均未设置,则为None。3.8 新版功能.
-
sys.excepthook(type, value, traceback)¶ 本函数会将所给的回溯和异常输出到
sys.stderr中。当抛出一个异常,且未被捕获时,解释器将调用
sys.excepthook并带有三个参数:异常类、异常实例和一个回溯对象。在交互式会话中,这会在控制权返回到提示符之前发生。在 Python 程序中,这会在程序退出之前发生。如果要自定义此类顶级异常的处理过程,可以将另一个 3 个参数的函数赋给sys.excepthook。引发一个 审计事件
sys.excepthook,附带参数hook,type,value,traceback。参见
sys.unraisablehook()函数处理无法抛出的异常,threading.excepthook()函数处理threading.Thread.run()抛出的异常。
-
sys.__breakpointhook__¶ -
sys.__displayhook__¶ -
sys.__excepthook__¶ -
sys.__unraisablehook__¶ 程序开始时,这些对象存有
breakpointhook、displayhook、excepthook和unraisablehook的初始值。保存它们是为了可以在breakpointhook、displayhook和excepthook、unraisablehook被破坏或被替换时恢复它们。3.7 新版功能: __breakpointhook__
3.8 新版功能: __unraisablehook__
-
sys.exc_info()¶ 本函数返回的元组包含三个值,它们给出当前正在处理的异常的信息。返回的信息仅限于当前线程和当前堆栈帧。如果当前堆栈帧没有正在处理的异常,则信息将从调用的下级堆栈帧或上级调用者等位置获取,依此类推,直到找到正在处理异常的堆栈帧为止。此处的“处理异常”被定义为“执行 except 子句”。任何堆栈帧都只能访问当前正在处理的异常的信息。
如果整个堆栈都没有正在处理的异常,则返回包含三个
None值的元组。否则返回值为(type, value, traceback)。它们的含义是:type 是正在处理的异常类型(它是BaseException的子类);value 是异常实例(异常类型的实例);traceback 是一个 回溯对象,该对象封装了最初发生异常时的调用堆栈。
-
sys.exec_prefix¶ 一个字符串,给出特定域的目录前缀,该目录中安装了与平台相关的 Python 文件,默认也是
'/usr/local'。该目录前缀可以在构建时使用 configure 脚本的--exec-prefix参数进行设置。具体而言,所有配置文件(如pyconfig.h头文件)都安装在目录exec_prefix/lib/pythonX.Y/config中,共享库模块安装在exec_prefix/lib/pythonX.Y/lib-dynload中,其中 X.Y 是 Python 的版本号,如3.2。注解
如果在一个 虚拟环境 中,那么该值将在
site.py中被修改,指向虚拟环境。Python 安装位置仍然可以用base_exec_prefix来获取。
-
sys.executable¶ 一个字符串,提供 Python 解释器的可执行二进制文件的绝对路径,仅在部分系统中此值有意义。如果 Python 无法获取其可执行文件的真实路径,则
sys.executable将为空字符串或None。
-
sys.exit([arg])¶ 从Python中退出。实现方式是抛出一个
SystemExit异常。异常抛出后try声明的 finally 分支语句的清除动作将被出发。此动作有可能打断更外层的退出尝试。可选参数 arg 可以是表示退出状态的整数(默认为 0),也可以是其他类型的对象。如果它是整数,则 shell 等将 0 视为“成功终止”,非零值视为“异常终止”。大多数系统要求该值的范围是 0--127,否则会产生不确定的结果。某些系统为退出代码约定了特定的含义,但通常尚不完善;Unix 程序通常用 2 表示命令行语法错误,用 1 表示所有其他类型的错误。传入其他类型的对象,如果传入
None等同于传入 0,如果传入其他对象则将其打印至stderr,且退出代码为 1。特别地,sys.exit("some error message")可以在发生错误时快速退出程序。由于
exit()最终“只是”抛出一个异常,因此当从主线程调用时,只会从进程退出;而异常不会因此被打断。在 3.6 版更改: 在 Python 解释器捕获
SystemExit后,如果在清理中发生错误(如清除标准流中的缓冲数据时出错),则退出状态码将变为 120。
-
sys.flags¶ 具名元组 flags 含有命令行标志的状态。这些属性是只读的。
attribute -- 属性
标志
debuginteractiveisolatedoptimizeno_user_siteno_siteignore_environmentverbosebytes_warningquiethash_randomizationdev_mode-Xdevutf8_mode-Xutf8在 3.2 版更改: 为新的
-q标志添加了quiet属性3.2.3 新版功能:
hash_randomization属性在 3.3 版更改: 删除了过时的
division_warning属性在 3.4 版更改: 为
-Iisolated标志添加了isolated属性。
-
sys.float_info¶ 一个 具名元组,存有浮点型的相关信息。它包含的是关于精度和内部表示的底层信息。这些值与标准头文件
float.h中为 C 语言定义的各种浮点常量对应,详情请参阅 1999 ISO/IEC C 标准 [C99] 的 5.2.4.2.2 节,'Characteristics of floating types(浮点型的特性)'。attribute -- 属性
float.h 宏
说明
epsilonDBL_EPSILON
大于 1.0 的最小值和 1.0 之间的差,表示为浮点数
digDBL_DIG
浮点数可以真实表示的最大十进制数字;见下文
mant_digDBL_MANT_DIG
浮点数精度:
radix基数下的浮点数有效位数DBL_MAX
最大可表示的正有限浮点数
max_expDBL_MAX_EXP
使得
radix**(e-1)是可表示的浮点数(非无穷)的最大整数 emax_10_expDBL_MAX_10_EXP
使得
10**e在可表示的浮点数(非无穷)范围内的最大整数 eDBL_MIN
可表示的最小正 规格化 浮点数
min_expDBL_MIN_EXP
使得
radix**(e-1)是规格化浮点数的最小整数 emin_10_expDBL_MIN_10_EXP
使得
10**e是规格化浮点数的最小整数 eradixFLT_RADIX
指数表示法中采用的基数
roundsFLT_ROUNDS
整数常数,表示算术运算中的舍入方式。它反映了解释器启动时系统的 FLT_ROUNDS 宏的值。关于可能的值及其含义的说明,请参阅 C99 标准 5.2.4.2.2 节。
关于
sys.float_info.dig属性的进一步说明。如果s是表示十进制数的字符串,而该数最多有sys.float_info.dig位有效数字,则将s转换为 float 再转回去将恢复原先相同十进制值的字符串:>>> 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'
但是对于超过
sys.float_info.dig位有效数字的字符串,转换前后并非总是相同:>>> s = '9876543211234567' # 16 significant digits is too many! >>> format(float(s), '.16g') # conversion changes value '9876543211234568'
-
sys.float_repr_style¶ 一个字符串,反映
repr()函数在浮点数上的行为。如果该字符串是'short',那么对于(非无穷的)浮点数x,repr(x)将会生成一个短字符串,满足float(repr(x)) == x的特性。这是 Python 3.1 及更高版本中的常见行为。否则float_repr_style的值将是'legacy',此时repr(x)的行为方式将与 Python 3.1 之前的版本相同。3.1 新版功能.
-
sys.getallocatedblocks()¶ 返回解释器当前已分配的内存块数,无论它们大小如何。本函数主要用于跟踪和调试内存泄漏。因为解释器有内部缓存,所以不同调用之间结果会变化。可能需要调用
_clear_type_cache()和gc.collect()使结果更容易预测。如果当前 Python 构建或实现无法合理地计算此信息,允许
getallocatedblocks()返回 0。3.4 新版功能.
-
sys.getcheckinterval()¶ Return the interpreter's "check interval"; see
setcheckinterval().3.2 版后已移除: Use
getswitchinterval()instead.
-
sys.getdefaultencoding()¶ 返回当前 Unicode 实现所使用的默认字符串编码名称。
-
sys.getdlopenflags()¶ 返回当前
dlopen()调用所使用的标志位的值。标志值对应的符号名称可以在os模块中找到(形如RTLD_xxx的常量,如os.RTLD_LAZY)。可用性: Unix。
-
sys.getfilesystemencoding()¶ 返回编码名称,该编码用于在 Unicode 文件名和 bytes 文件名之间转换。为获得最佳兼容性,任何时候都应使用 str 表示文件名,尽管用字节来表示文件名也是支持的。函数如果需要接受或返回文件名,它应支持 str 或 bytes,并在内部将其转换为系统首选的表示形式。
该编码始终是 ASCII 兼容的。
应使用
os.fsencode()和os.fsdecode()来保证所采用的编码和错误模式都是正确的。在UTF-8模式下,任何平台上的编码均为
utf-8。在macOS上,编码为
'utf-8'。在Unix上,编码是语言环境编码。
在Windows上取决于用户配置,编码可能是
'utf-8'或'mbcs'。在Android上,编码为
'utf-8'。在VxWorks上,编码为
'utf-8'。
在 3.2 版更改:
getfilesystemencoding()的结果将不再有可能是None。在 3.6 版更改: Windows 不再保证会返回
'mbcs'。详情请参阅 PEP 529 和_enablelegacywindowsfsencoding()。在 3.7 版更改: 在UTF-8模式下返回 'utf-8' 。
-
sys.getfilesystemencodeerrors()¶ 返回错误回调函数的名称,该错误回调函数将在 Unicode 文件名和 bytes 文件名转换时生效。编码的名称是由
getfilesystemencoding()返回的。应使用
os.fsencode()和os.fsdecode()来保证所采用的编码和错误模式都是正确的。3.6 新版功能.
-
sys.getrefcount(object)¶ 返回 object 的引用计数。返回的计数通常比预期的多一,因为它包括了作为
getrefcount()参数的这一次(临时)引用。
-
sys.getrecursionlimit()¶ 返回当前的递归限制值,即 Python 解释器堆栈的最大深度。此限制可防止无限递归导致的 C 堆栈溢出和 Python 崩溃。该值可以通过
setrecursionlimit()设置。
-
sys.getsizeof(object[, default])¶ 返回对象的大小(以字节为单位)。该对象可以是任何类型。所有内建对象返回的结果都是正确的,但对于第三方扩展不一定正确,因为这与具体实现有关。
只计算直接分配给对象的内存消耗,不计算它所引用的对象的内存消耗。
对象不提供计算大小的方法时,如果有给出 default 则返回它,否则抛出
TypeError异常。如果对象由垃圾回收器管理,则
getsizeof()将调用对象的__sizeof__方法,并在上层添加额外的垃圾回收器。可以参考 recursive sizeof recipe 中的示例,关于递归调用
getsizeof()来得到各个容器及其所有内容物的大小。
-
sys.getswitchinterval()¶ 返回解释器的“线程切换间隔时间”,请参阅
setswitchinterval()。3.2 新版功能.
-
sys._getframe([depth])¶ 返回来自调用栈的一个帧对象。如果传入可选整数 depth,则返回从栈顶往下相应调用层数的帧对象。如果该数比调用栈更深,则抛出
ValueError。depth 的默认值是 0,返回调用栈顶部的帧。引发一个 审计事件
sys._getframe,没有附带参数。CPython implementation detail: 这个函数应该只在内部为了一些特定的目的使用。不保证它在所有 Python 实现中都存在。
-
sys.getprofile()¶ 返回由
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:
常数
含义
1 (VER_NT_WORKSTATION)系统是工作站。
2 (VER_NT_DOMAIN_CONTROLLER)系统是域控制器。
3 (VER_NT_SERVER)系统是服务器,但不是域控制器。
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.
可用性: Windows。
在 3.2 版更改: Changed to a named tuple and added service_pack_minor, service_pack_major, suite_mask, and product_type.
在 3.6 版更改: 添加了 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
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.hash_info¶ A named tuple giving parameters of the numeric hash implementation. For more details about hashing of numeric types, see 数字类型的哈希运算.
attribute -- 属性
说明
width用于哈希值的位宽度
modulus用于数字散列方案的素数模数P。
inf为正无穷大返回的哈希值
nan为nan返回的哈希值
imag用于复数虚部的乘数
algorithm字符串、字节和内存视图的哈希算法的名称
hash_bits哈希算法的内部输出大小。
seed_bits散列算法的种子密钥的大小
3.2 新版功能.
在 3.4 版更改: 添加了 algorithm, hash_bits 和 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.hexversion >= 0x010502F0: # use some advanced feature ... else: # use an alternative implementation or warn the user ...
This is called
hexversionsince it only really looks meaningful when viewed as the result of passing it to the built-inhex()function. The named tuplesys.version_infomay be used for a more human-friendly encoding of the same information.More details of
hexversioncan be found at API 和 ABI 版本管理.
-
sys.implementation¶ An object containing information about the implementation of the currently running Python interpreter. The following attributes are required to exist in all Python implementations.
name is the implementation's identifier, e.g.
'cpython'. The actual string is defined by the Python implementation, but it is guaranteed to be lower case.version is a named tuple, in the same format as
sys.version_info. It represents the version of the Python implementation. This has a distinct meaning from the specific version of the Python language to which the currently running interpreter conforms, whichsys.version_inforepresents. For example, for PyPy 1.8sys.implementation.versionmight besys.version_info(1, 8, 0, 'final', 0), whereassys.version_infowould besys.version_info(2, 7, 2, 'final', 0). For CPython they are the same value, since it is the reference implementation.hexversion is the implementation version in hexadecimal format, like
sys.hexversion.cache_tag is the tag used by the import machinery in the filenames of cached modules. By convention, it would be a composite of the implementation's name and version, like
'cpython-33'. However, a Python implementation may use some other value if appropriate. Ifcache_tagis set toNone, it indicates that module caching should be disabled.sys.implementationmay contain additional attributes specific to the Python implementation. These non-standard attributes must start with an underscore, and are not described here. Regardless of its contents,sys.implementationwill 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.3.3 新版功能.
注解
The addition of new required attributes must go through the normal PEP process. See PEP 421 for more information.
-
sys.int_info¶ A named tuple that holds information about Python's internal representation of integers. The attributes are read only.
属性
说明
bits_per_digitnumber of bits held in each digit. Python integers are stored internally in base
2**int_info.bits_per_digitsizeof_digit用于表示数字的C类型的字节大小
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 the
PYTHONSTARTUPfile is read, so that you can set this hook there. Thesitemodule sets this.Raises an auditing event
cpython.run_interactivehookwith the hook object as the argument when the hook is called on startup.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. 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.
Interned strings are not immortal; you must keep a reference to the return value of
intern()around to benefit from it.
-
sys.is_finalizing()¶ Return
Trueif the Python interpreter is shutting down,Falseotherwise.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 is
import pdb; pdb.pm()to enter the post-mortem debugger; seepdbmodule for more information.)The meaning of the variables is the same as that of the return values from
exc_info()above.
-
sys.maxsize¶ An integer giving the maximum value a variable of type
Py_ssize_tcan take. It's usually2**31 - 1on a 32-bit platform and2**63 - 1on a 64-bit platform.
-
sys.maxunicode¶ An integer giving the value of the largest Unicode code point, i.e.
1114111(0x10FFFFin hexadecimal).在 3.3 版更改: Before PEP 393,
sys.maxunicodeused to be either0xFFFFor0x10FFFF, 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, orNoneif the module cannot be found.参见
importlib.abc.MetaPathFinderThe abstract base class defining the interface of finder objects on
meta_path.importlib.machinery.ModuleSpecThe concrete class which
find_spec()should return instances of.
在 3.4 版更改: Module specs were introduced in Python 3.4, by PEP 451. Earlier versions of Python looked for a method called
find_module(). This is still called as a fallback if ameta_pathentry 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.
-
sys.path¶ A list of strings that specifies the search path for modules. Initialized from the environment variable
PYTHONPATH, plus an installation-dependent default.As initialized upon program startup, the first item of this list,
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),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 ofPYTHONPATH.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_hooks¶ A list of callables that take a path argument to try to create a finder for the path. If a finder can be created, it is to be returned by the callable, else raise
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_hooksand the values are the finders that are found. If a path is a valid file system path but no finder is found onsys.path_hooksthenNoneis stored.Originally specified in PEP 302.
在 3.3 版更改:
Noneis stored instead ofimp.NullImporterwhen 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.For Unix systems, except on Linux and AIX, this is the lowercased OS name as returned by
uname -swith the first part of the version as returned byuname -rappended, 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...
对于其他系统,值是:
系统
平台值AIX
'aix'Linux
'linux'Windows
'win32'Windows/Cygwin
'cygwin'macOS
'darwin'在 3.3 版更改: On Linux,
sys.platformdoesn'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 thestartswithidiom presented above.在 3.8 版更改: On AIX,
sys.platformdoesn'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 thestartswithidiom presented above.参见
os.namehas a coarser granularity.os.uname()gives system-dependent version information.platform模块对系统的标识有更详细的检查。
-
sys.prefix¶ A string giving the site-specific directory prefix where the platform independent Python files are installed; by default, this is the string
'/usr/local'. This can be set at build time with the--prefixargument to the configure script. The main collection of Python library modules is installed in the directoryprefix/lib/pythonX.Ywhile the platform independent header files (all exceptpyconfig.h) are stored inprefix/include/pythonX.Y, 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_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, itsstr()is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt.
-
sys.setcheckinterval(interval)¶ Set the interpreter's "check interval". This integer value determines how often the interpreter checks for periodic things such as thread switches and signal handlers. The default is
100, meaning the check is performed every 100 Python virtual instructions. Setting it to a larger value may increase performance for programs using threads. Setting it to a value<=0 checks every virtual instruction, maximizing responsiveness as well as overhead.3.2 版后已移除: This function doesn't have an effect anymore, as the internal logic for thread switching and asynchronous tasks has been rewritten. Use
setswitchinterval()instead.
-
sys.setdlopenflags(n)¶ Set the flags used by the interpreter for
dlopen()calls, such as when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called assys.setdlopenflags(0). To share symbols across extension modules, call assys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag values can be found in theosmodule (RTLD_xxxconstants, e.g.os.RTLD_LAZY).可用性: Unix。
-
sys.setprofile(profilefunc)¶ 设置系统的性能分析函数,该函数使得在 Python 中能够实现一个 Python 源代码性能分析器。关于 Python Profiler 的更多信息请参阅 Python Profilers 分析器 章节。性能分析函数的调用方式类似于系统的跟踪函数(参阅
settrace()),但它是通过不同的事件调用的,例如,不是每执行一行代码就调用它一次(仅在调用某函数和从某函数返回时才会调用性能分析函数,但即使某函数发生异常也会算作返回事件)。该函数是特定于线程的,但是性能分析器无法得知线程之间的上下文切换,因此在存在多个线程的情况下使用它是没有意义的。另外,因为它的返回值不会被用到,所以可以简单地返回None。性能分析函数中的错误将导致其自身被解除设置。性能分析函数应接收三个参数:frame、event 和 arg。frame 是当前的堆栈帧。event 是一个字符串:
'call'、'return'、'c_call'、'c_return'或'c_exception'。arg 取决于事件类型。引发一个 审计事件
sys.setprofile,不附带任何参数。这些事件具有以下含义:
'call'A function is called (or some other code block entered). The profile function is called; arg is
None.'return'A function (or other code block) is about to return. The profile function is called; arg is the value that will be returned, or
Noneif the event is caused by an exception being raised.'c_call'A C function is about to be called. This may be an extension function or a built-in. arg is the C function object.
'c_return'A C function has returned. arg is the C function object.
'c_exception'A C function has raised an exception. arg is the C function object.
-
sys.setrecursionlimit(limit)¶ Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing 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
RecursionErrorexception is raised.在 3.5.1 版更改: A
RecursionErrorexception is now raised if the new limit is too low at the current recursion depth.
-
sys.setswitchinterval(interval)¶ 设置解释器的线程切换间隔时间(单位为秒)。该浮点数决定了“时间片”的理想持续时间,时间片将分配给同时运行的 Python 线程。请注意,实际值可能更高,尤其是使用了运行时间长的内部函数或方法时。同时,在时间间隔末尾调度哪个线程是操作系统的决定。解释器没有自己的调度程序。
3.2 新版功能.
-
sys.settrace(tracefunc)¶ Set the system's trace function, which allows you to implement a Python source code debugger in 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().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, orNoneif 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
Noneto turn off tracing in that scope.If there is any error occurred in the trace function, it will be unset, just like
settrace(None)is called.这些事件具有以下含义:
'call'A function is called (or some other code block entered). The global trace function is called; arg is
None; the return value specifies the local trace function.'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
None; the return value specifies the new local trace function. SeeObjects/lnotab_notes.txtfor a detailed explanation of how this works. Per-line events may be disabled for a frame by settingf_trace_linestoFalseon 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
Noneif the event is caused by an exception being raised. 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
disfor opcode details). The local trace function is called; arg isNone; the return value specifies the new local trace function. Per-opcode events are not emitted by default: they must be explicitly requested by settingf_trace_opcodestoTrueon the frame.
Note that as an exception is propagated down the chain of callers, an
'exception'event is generated at each level.For more fine-grained usage, it's possible to set a trace function by assigning
frame.f_trace = tracefuncexplicitly, 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, whichsettrace()doesn't do. Note that in order for this to work, a global tracing function must have been installed withsettrace()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 returnsNoneto disable itself immediately on each frame).For more information on code and frame objects, refer to 标准类型层级结构.
Raises an auditing event
sys.settracewith no arguments.CPython implementation detail: The
settrace()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.在 3.7 版更改:
'opcode'event type added;f_trace_linesandf_trace_opcodesattributes 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. The finalizer will be called when an asynchronous generator is about to be garbage collected.
Raises an auditing event
sys.set_asyncgen_hooks_firstiterwith no arguments.Raises an auditing event
sys.set_asyncgen_hooks_finalizerwith no arguments.Two auditing events are raised because the underlying API consists of two calls, each of which must raise its own event.
3.6 新版功能: See PEP 525 for more details, and for a reference example of a finalizer method see the implementation of
asyncio.Loop.shutdown_asyncgensin Lib/asyncio/base_events.py注解
This function has been added on a provisional basis (see PEP 411 for details.)
-
sys.set_coroutine_origin_tracking_depth(depth)¶ Allows enabling or disabling coroutine origin tracking. When enabled, the
cr_originattribute 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_originwill be None.To enable, pass a depth value greater than zero; this sets the number of frames whose information will be captured. To disable, pass set depth to zero.
This setting is thread-specific.
3.7 新版功能.
注解
This function has been added on a provisional basis (see PEP 411 for details.) Use it only for debugging purposes.
-
sys._enablelegacywindowsfsencoding()¶ Changes the default filesystem encoding and errors mode to 'mbcs' and 'replace' respectively, for consistency with versions of Python prior to 3.6.
This is equivalent to defining the
PYTHONLEGACYWINDOWSFSENCODINGenvironment variable before launching Python.可用性: Windows。
3.6 新版功能: 有关更多详细信息,请参阅 PEP 529。
-
sys.stdin¶ -
sys.stdout¶ -
sys.stderr¶ File objects used by the interpreter for standard input, output and errors:
stdinis used for all interactive input (including calls toinput());stdoutis 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.
These streams are regular text files like those returned by the
open()function. Their parameters are chosen as follows:The character encoding is platform-dependent. Non-Windows platforms use the locale encoding (see
locale.getpreferredencoding()).On Windows, UTF-8 is used for the console device. Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where
isatty()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. 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
PYTHONIOENCODINGenvironment variable before starting Python or by using the new-Xutf8command line option andPYTHONUTF8environment variable. However, for the Windows console, this only applies whenPYTHONLEGACYWINDOWSSTDIOis also set.When interactive,
stdoutandstderrstreams are line-buffered. Otherwise, they are block-buffered like regular text files. You can override this value with the-ucommand-line option.
注解
To write or read binary data from/to the standard streams, use the underlying binary
bufferobject. 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.StringIOwhich do not support thebufferattribute.
-
sys.__stdin__¶ -
sys.__stdout__¶ -
sys.__stderr__¶ These objects contain the original values of
stdin,stderrandstdoutat the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if thesys.std*object has been redirected.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.
注解
Under some conditions
stdin,stdoutandstderras 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.thread_info¶ A named tuple holding information about the thread implementation.
属性
说明
name线程实现的名称:
'nt': Windows 线程'pthread': POSIX 线程'solaris': Solaris 线程
lock锁实现的名称:
'semaphore': 锁使用信号量'mutex+cond': 锁使用互斥和条件变量None如果此信息未知
线程库的名称和版本。它是一个字符串,如果此信息未知,则为
None。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. When set to0or less, all traceback information is suppressed and only the exception type and value are printed.
-
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:
exc_type: 异常类型
exc_value: 异常值,可以是
None.exc_traceback: 异常回溯,可以是
None.err_msg: 错误信息,可以是
None.object: 导致异常的对象,可以为
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.使用定制钩子存放 exc_value 可能会创建引用循环。 它应当在不再需要异常时被显式地清空以打破引用循环。
Storing object using a custom hook can resurrect it if it is set to an object which is being finalized. Avoid storing object after the custom hook completes to avoid resurrecting objects.
See also
excepthook()which handles uncaught exceptions.Raise an auditing event
sys.unraisablehookwith argumentshook,unraisablewhen an exception that cannot be handled occurs. Theunraisableobject is the same as what will be passed to the hook. If no hook has been set,hookmay beNone.3.8 新版功能.
-
sys.version¶ A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use
version_infoand the functions provided by theplatformmodule.
-
sys.api_version¶ The C API version for this interpreter. Programmers may find this useful when debugging version conflicts between Python and extension modules.
-
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_infovalue 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.majorand so on.在 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
warningsmodule for more information on the warnings framework.
-
sys.winver¶ The version number used to form registry keys on Windows platforms. This is stored as string resource 1000 in the Python DLL. The value is normally the first three characters of
version. It is provided in thesysmodule for informational purposes; modifying this value has no effect on the registry keys used by Python.可用性: Windows。
-
sys._xoptions¶ A dictionary of the various implementation-specific flags passed through the
-Xcommand-line option. Option names are either mapped to their values, if given explicitly, or toTrue. 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: This is a CPython-specific way of accessing options passed through
-X. Other implementations may export them through other means, or not at all.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.
