tp最新版官网|sys

作者: tp最新版官网
2024-03-07 21:20:39

Python sys 模块详解 - 知乎

Python sys 模块详解 - 知乎首发于好好学习切换模式写文章登录/注册Python sys 模块详解轩辕御龙ZGNBPython sys 模块详解1. 简介“sys”即“system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。2. 常用功能2.1 sys.argv“argv”即“argument value”的简写,是一个列表对象,其中存储的是在命令行调用 Python 脚本时提供的“命令行参数”。这个列表中的第一个参数是被调用的脚本名称,也就是说,调用 Python 解释器的“命令”(python)本身并没有被加入这个列表当中。这个地方要注意一下,因为这一点跟 C 程序的行为有所不同,C 程序读取命令行参数是从头开始的。举例来说,在当前目录下新建一个 Python 文件sys_argv_example.py,其内容为: import sys

print("The list of command line arguments:\n", sys.argv)在命令行运行该脚本: $ python sys_argv_example.py

The list of command line arguments:

['example.py']

加上几个参数试试: $ python sys_argv_example.py arg1 arg2 arg3

The list of command line arguments:

['example.py', 'arg1', 'arg2', 'arg3']

​利用好这个属性,可以极大增强 Python 脚本的交互性。2.2 sys.platform在《第26天: Python 标准库之 os 模块详解》中,我们提到过“查看sys模块中的sys.platform属性可以得到关于运行平台更详细的信息”,这里我们就来试试: >>> import sys

>>> sys.platform

'win32'在 Linux 上: >>> sys.platform

'linux'比较一下os.name的结果,不难发现,sys.platform的信息更加准确。2.3 sys.byteorder“byteorder”即“字节序”,指的是在计算机内部存储数据时,数据的低位字节存储在存储空间中的高位还是低位。“小端存储”时,数据的低位也存储在存储空间的低位地址中,此时sys.byteorder的值为“little”。如果不注意,在按地址顺序打印内容的时候,可能会把小端存储的内容打错。当前大部分机器都是使用的小端存储。所以不出意外的话,你的机器上执行下述交互语句也应当跟我的结果一样: >>> sys.byteorder

'little'而另外还存在一种存储顺序是“大端存储”,即数据的高位字节存储在存储空间的低位地址上,此时sys.byteorder的值为“big”。这种方式看起来好像很合理也很自然,因为我们一般在书面表示的时候都将低位地址写在左边,高位地址写在右边,大端存储的顺序就很符合人类的阅读习惯。但实际上对机器而言,内存地址并没有左右之分,所谓的“自然”其实并不存在。抱歉我并没有使用大端存储的机器可以用作演示,因此只能说如果是大端存储的机器上运行 Python,输出结果应该像下面这样,也就是说下面这个示例并非我得到的真实运行结果,仅供参考: >>> sys.byteorder

'big'2.4 sys.executable该属性是一个字符串,在正常情况下,其值是当前运行的 Python 解释器对应的可执行程序所在的绝对路径。比如在 Windows 上使用 Anaconda 安装的 Python,该属性的值就是: >>> sys.executable

'E:\\Anaconda\\Anaconda\\python.exe'2.5 sys.modules该属性是一个字典,包含的是各种已加载的模块的模块名到模块具体位置的映射。通过手动修改这个字典,可以重新加载某些模块;但要注意,切记不要大意删除了一些基本的项,否则可能会导致 Python 整个儿无法运行。关于其具体的值,由于内容过多,就不在此给出示例了,读者可以自行查看。2.6 sys.builtin_module_names该属性是一个字符串元组,其中的元素均为当前所使用的的 Python 解释器内置的模块名称。注意区别sys.modules和sys.builtin_module_names——前者的关键字(keys)列出的是导入的模块名,而后者则是解释器内置的模块名。其值示例如下:>>> sys.builtin_module_names

('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_contextvars', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')

2.7 sys.path A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. 该属性是一个由字符串组成的列表,其中各个元素表示的是 Python 搜索模块的路径;在程序启动期间被初始化。其中第一个元素(也就是path[0])的值是最初调用 Python 解释器的脚本所在的绝对路径;如果是在交互式环境下查看sys.path的值,就会得到一个空字符串。命令行运行脚本(脚本代码见示例 sys_path_example.py):$ python sys_path_example.py

The path[0] = D:\justdopython\sys_example

交互式环境查看属性第一个元素:>>> sys.path[0]

''

3. 进阶功能3.1 sys.stdin即 Python 的标准输入通道。通过改变这个属性为其他的类文件(file-like)对象,可以实现输入的重定向,也就是说可以用其他内容替换标准输入的内容。所谓“标准输入”,实际上就是通过键盘输入的字符。在示例(sys_stdin_example.py)中,我们尝试把这个属性的值改为一个打开的文件对象hello_python.txt,其中包含如下的内容:Hello Python!

Just do Python, go~

Go, Go, GO!

由于input()使用的就是标准输入流,因此通过修改sys.stdin的值,我们使用老朋友input()函数,也可以实现对文件内容的读取,程序运行效果如下:$ python sys_stdin_example.py

Hello Python!

Just do Python, go~

Go, Go, GO!

3.2 sys.stdout与上一个“标准输入”类似,sys.stdout则是代表“标准输出”的属性。通过将这个属性的值修改为某个文件对象,可以将本来要打印到屏幕上的内容写入文件。比如运行示例程序sys_stdout_example.py,用来临时生成日志也是十分方便的:import sys

# 以附加模式打开文件,若不存在则新建

with open("count_log.txt", 'a', encoding='utf-8') as f:

sys.stdout = f

for i in range(10):

print("count = ", i)

3.3 sys.err与前面两个属性类似,只不过该属性标识的是标准错误,通常也是定向到屏幕的,可以粗糙地认为是一个输出错误信息的特殊的标准输出流。由于性质类似,因此不做演示。此外,sys模块中还存在几个“私有”属性:sys.__stdin__,sys.__stdout__,sys.__stderr__。这几个属性中保存的就是最初定向的“标准输入”、“标准输出”和“标准错误”流。在适当的时侯,我们可以借助这三个属性将sys.stdin、sys.stdout和sys.err恢复为初始值。3.4 sys.getrecursionlimit() 和 sys.setrecursionlimit()sys.getrecursionlimit()和sys.setrecursionlimit()是成对的。前者可以获取 Python 的最大递归数目,后者则可以设置最大递归数目。因为初学阶段很少用到,因此只做了解。3.5 sys.getrefcount()在《第12天:Python 之引用》中我们其实已经用到过这个函数,其返回值是 Python 中某个对象被引用的次数。关于“引用”的知识可以回去看看这篇文章。3.6 sys.getsizeof()这个函数的作用与 C 语言中的sizeof运算符类似,返回的是作用对象所占用的字节数。比如我们就可以看看一个整型对象1在内存中的大小:>>> sys.getsizeof(1)

28

注意,在 Python 中,某类对象的大小并非一成不变的:>>> sys.getsizeof(2**30-1)

28

>>> sys.getsizeof(2**30)

32

3.7 sys.int_info 和 sys.float_info这两个属性分别给出了 Python 中两个重要的数据类型的相关信息。其中sys.int_info的值为:>>> sys.int_info

sys.int_info(bits_per_digit=30, sizeof_digit=4)

在文档中的解释为:属性解释bits_per_digitnumber of bits held in each digit. Python integers are stored internally in base 2**int_info.bits_per_digitsizeof_digitsize in bytes of the C type used to represent a digit指的是 Python 以 2 的sys.int_info.bits_per_digit次方为基来表示整数,也就是说它是“2 的sys.int_info.bits_per_digit次方进制”的数。这样的数每一个为都用 C 类中的 4 个字节来存储。换句话说,每“进 1 位”(即整数值增加2 的sys.int_info.bits_per_digit次方),就需要多分配 4 个字节用以保存某个整数。因此在sys.getsizeof()的示例中,我们可以看到2**30-1和2**30之间,虽然本身只差了 1,但是所占的字节后者却比前者多了 4。而sys.float_info的值则是:>>> sys.float_info

sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

其中各项具体的含义就不在这里继续展开了,感兴趣的同学可以参看文档和《深入理解计算机系统》等讲解组成原理的书。4. 一个有趣的功能接下来让我们放松一下。每次打开 Python 的交互式界面,我们都会看到一个提示符>>>。不知道你有没有想过要把这个东西换成另外的什么呢?反正我没想过哈哈——至少在文档中看到这两个属性之前,我确实没有想过。哪两个属性呢?就这俩货:sys.ps1和sys.ps2所谓“ps”,应当是“prompts”的简写,即“提示符”。这两个属性中,sys.ps1代表的是一级提示符,也就是进入 Python 交互界面之后就会出现的那一个>>>;而第二个sys.ps2则是二级提示符,是在同一级内容没有输入完,换行之后新行行首的提示符...。当然,两个属性都是字符串。好了,知道怎么回事儿就好办了。现在我们就来一个: >>> sys.ps1 = "justdopython "

justdopython li = [1,2,3]

justdopython li[0]

1

justdopython

​提示符已经被改变了,当然,有点长,不大美观哈哈。咱们换一下: justdopython sys.ps1 = "ILoveYou: "

ILoveYou: print("你可真是个小机灵鬼儿!")

你可真是个小机灵鬼儿!

ILoveYou:

​有点儿意思吧?注意不要忘了在字符串最后加个空格,否则提示符就会和你输入的内容混杂在一起了,会十分难看的哟~示例代码:python-100-days参考资料Python3 标准库-sys 模块发布于 2020-06-26 17:10Python 3.xPythonPython 标准库​赞同 93​​6 条评论​分享​喜欢​收藏​申请转载​文章被以下专栏收录好

Python 基础(二十):sys 模块 - 知乎

Python 基础(二十):sys 模块 - 知乎首发于Python切换模式写文章登录/注册Python 基础(二十):sys 模块Python小二1. 简介sys 模块主要负责与 Python 解释器进行交互,该模块提供了一系列用于控制 Python 运行环境的函数和变量。之前我们说过 os 模块,该模块与 sys 模块从名称上看着好像有点类似,实际上它们之间是没有什么关系的,os 模块主要负责与操作系统进行交互。2. 使用我们先整体看一下 sys 模块都包含哪些内容,如下所示:>>> import sys

>>> dir(sys)

['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']对于一些相对常用的变量和函数,我们下面再来具体看一下。argv 返回传递给 Python 脚本的命令行参数列表。看下示例:import sys

if __name__ == '__main__':

args = sys.argv

print(args)

print(args[1])上面文件名为:test.py,我们在控制台使用命令:python test.py 123 abc 执行一下,执行结果如下:['test.py', '123', 'abc']

123version 返回 Python 解释器的版本信息。winver返回 Python 解释器主版号。platform 返回操作系统平台名称。path返回模块的搜索路径列表。maxsize返回支持的最大整数值。maxunicode返回支持的最大 Unicode 值。copyright 返回 Python 版权信息。modules 以字典类型返回系统导入的模块。byteorder返回本地字节规则的指示器。executable返回 Python 解释器所在路径。import sys

print(sys.version)

print(sys.winver)

print(sys.platform)

print(sys.path)

print(sys.maxsize)

print(sys.maxunicode)

print(sys.copyright)

print(sys.modules)

print(sys.byteorder)

print(sys.executable)stdout 标准输出。看下示例:import sys

# 下面两行代码等价

sys.stdout.write('Hi' + '\n')

print('Hi')stdin 标准输入。看下示例:import sys

s1 = input()

s2 = sys.stdin.readline()

print(s1)

print(s2)stderr 错误输出。看下示例:import sys

sys.stderr.write('this is a error message')exit()退出当前程序。看下示例:import sys

print('Hi')

sys.exit()

print('Jhon')getdefaultencoding()返回当前默认字符串编码的名称。getrefcount(obj)返回对象的引用计数。getrecursionlimit()返回支持的递归深度。getsizeof(object[, default])以字节为单位返回对象的大小。setswitchinterval(interval)设置线程切换的时间间隔。getswitchinterval()返回线程切换时间间隔。import sys

print(sys.getdefaultencoding())

print(sys.getrefcount('123456'))

print(sys.getrecursionlimit())

print(sys.getsizeof('abcde'))

sys.setswitchinterval(1)

print(sys.getswitchinterval())发布于 2020-05-25 19:45PythonPython 入门Python 开发​赞同 2​​添加评论​分享​喜欢​收藏​申请转载​文章被以下专栏收录Python分享基础、实用、有趣的 Python

Python 标准库之 sys 模块详解_sys函数-CSDN博客

>

Python 标准库之 sys 模块详解_sys函数-CSDN博客

Python 标准库之 sys 模块详解

最新推荐文章于 2024-01-27 14:09:39 发布

轩辕御龙

最新推荐文章于 2024-01-27 14:09:39 发布

阅读量6.4k

收藏

46

点赞数

7

分类专栏:

Python

文章标签:

Python

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/w573719227/article/details/102527967

版权

Python

专栏收录该内容

16 篇文章

1 订阅

订阅专栏

Python sys 模块详解

1. 简介

“sys”即“system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。

2. 常用功能

2.1 sys.argv

“argv”即“argument value”的简写,是一个列表对象,其中存储的是在命令行调用 Python 脚本时提供的“命令行参数”。

这个列表中的第一个参数是被调用的脚本名称,也就是说,调用 Python 解释器的“命令”(python)本身并没有被加入这个列表当中。这个地方要注意一下,因为这一点跟 C 程序的行为有所不同,C 程序读取命令行参数是从头开始的。

举例来说,在当前目录下新建一个 Python 文件sys_argv_example.py,其内容为:

import sys

print("The list of command line arguments:\n", sys.argv)

在命令行运行该脚本:

$ python sys_argv_example.py

The list of command line arguments:

['example.py']

加上几个参数试试:

$ python sys_argv_example.py arg1 arg2 arg3

The list of command line arguments:

['example.py', 'arg1', 'arg2', 'arg3']

利用好这个属性,可以极大增强 Python 脚本的交互性。

2.2 sys.platform

在《第26天: Python 标准库之 os 模块详解》中,我们提到过“查看sys模块中的sys.platform属性可以得到关于运行平台更详细的信息”,这里我们就来试试:

>>> import sys

>>> sys.platform

'win32'

在 Linux 上:

>>> sys.platform

'linux'

比较一下os.name的结果,不难发现,sys.platform的信息更加准确。

2.3 sys.byteorder

“byteorder”即“字节序”,指的是在计算机内部存储数据时,数据的低位字节存储在存储空间中的高位还是低位。

“小端存储”时,数据的低位也存储在存储空间的低位地址中,此时sys.byteorder的值为“little”。如果不注意,在按地址顺序打印内容的时候,可能会把小端存储的内容打错。当前大部分机器都是使用的小端存储。

所以不出意外的话,你的机器上执行下述交互语句也应当跟我的结果一样:

>>> sys.byteorder

'little'

而另外还存在一种存储顺序是“大端存储”,即数据的高位字节存储在存储空间的低位地址上,此时sys.byteorder的值为“big”。

这种方式看起来好像很合理也很自然,因为我们一般在书面表示的时候都将低位地址写在左边,高位地址写在右边,大端存储的顺序就很符合人类的阅读习惯。但实际上对机器而言,内存地址并没有左右之分,所谓的“自然”其实并不存在。

抱歉我并没有使用大端存储的机器可以用作演示,因此只能说如果是大端存储的机器上运行 Python,输出结果应该像下面这样,也就是说下面这个示例并非我得到的真实运行结果,仅供参考:

>>> sys.byteorder

'big'

2.4 sys.executable

该属性是一个字符串,在正常情况下,其值是当前运行的 Python 解释器对应的可执行程序所在的绝对路径。

比如在 Windows 上使用 Anaconda 安装的 Python,该属性的值就是:

>>> sys.executable

'E:\\Anaconda\\Anaconda\\python.exe'

2.5 sys.modules

该属性是一个字典,包含的是各种已加载的模块的模块名到模块具体位置的映射。

通过手动修改这个字典,可以重新加载某些模块;但要注意,切记不要大意删除了一些基本的项,否则可能会导致 Python 整个儿无法运行。

关于其具体的值,由于内容过多,就不在此给出示例了,读者可以自行查看。

2.6 sys.builtin_module_names

该属性是一个字符串元组,其中的元素均为当前所使用的的 Python 解释器内置的模块名称。

注意区别sys.modules和sys.builtin_module_names——前者的关键字(keys)列出的是导入的模块名,而后者则是解释器内置的模块名。

其值示例如下:

>>> sys.builtin_module_names

('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_contextvars', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')

2.7 sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

该属性是一个由字符串组成的列表,其中各个元素表示的是 Python 搜索模块的路径;在程序启动期间被初始化。

其中第一个元素(也就是path[0])的值是最初调用 Python 解释器的脚本所在的绝对路径;如果是在交互式环境下查看sys.path的值,就会得到一个空字符串。

命令行运行脚本(脚本代码见示例 sys_path_example.py):

$ python sys_path_example.py

The path[0] = D:\justdopython\sys_example

交互式环境查看属性第一个元素:

>>> sys.path[0]

''

3. 进阶功能

3.1 sys.stdin

即 Python 的标准输入通道。通过改变这个属性为其他的类文件(file-like)对象,可以实现输入的重定向,也就是说可以用其他内容替换标准输入的内容。

所谓“标准输入”,实际上就是通过键盘输入的字符。

在示例(sys_stdin_example.py)中,我们尝试把这个属性的值改为一个打开的文件对象hello_python.txt,其中包含如下的内容:

Hello Python!

Just do Python, go~

Go, Go, GO!

由于input()使用的就是标准输入流,因此通过修改sys.stdin的值,我们使用老朋友input()函数,也可以实现对文件内容的读取,程序运行效果如下:

$ python sys_stdin_example.py

Hello Python!

Just do Python, go~

Go, Go, GO!

3.2 sys.stdout

与上一个“标准输入”类似,sys.stdout则是代表“标准输出”的属性。

通过将这个属性的值修改为某个文件对象,可以将本来要打印到屏幕上的内容写入文件。

比如运行示例程序sys_stdout_example.py,用来临时生成日志也是十分方便的:

import sys

# 以附加模式打开文件,若不存在则新建

with open("count_log.txt", 'a', encoding='utf-8') as f:

sys.stdout = f

for i in range(10):

print("count = ", i)

3.3 sys.err

与前面两个属性类似,只不过该属性标识的是标准错误,通常也是定向到屏幕的,可以粗糙地认为是一个输出错误信息的特殊的标准输出流。由于性质类似,因此不做演示。

此外,sys模块中还存在几个“私有”属性:sys.__stdin__,sys.__stdout__,sys.__stderr__。这几个属性中保存的就是最初定向的“标准输入”、“标准输出”和“标准错误”流。在适当的时侯,我们可以借助这三个属性将sys.stdin、sys.stdout和sys.err恢复为初始值。

3.4 sys.getrecursionlimit() 和 sys.setrecursionlimit()

sys.getrecursionlimit()和sys.setrecursionlimit()是成对的。前者可以获取 Python 的最大递归数目,后者则可以设置最大递归数目。因为初学阶段很少用到,因此只做了解。

3.5 sys.getrefcount()

在《第12天:Python 之引用》中我们其实已经用到过这个函数,其返回值是 Python 中某个对象被引用的次数。关于“引用”的知识可以回去看看这篇文章。

3.6 sys.getsizeof()

这个函数的作用与 C 语言中的sizeof运算符类似,返回的是作用对象所占用的字节数。

比如我们就可以看看一个整型对象1在内存中的大小:

>>> sys.getsizeof(1)

28

注意,在 Python 中,某类对象的大小并非一成不变的:

>>> sys.getsizeof(2**30-1)

28

>>> sys.getsizeof(2**30)

32

3.7 sys.int_info 和 sys.float_info

这两个属性分别给出了 Python 中两个重要的数据类型的相关信息。

其中sys.int_info的值为:

>>> sys.int_info

sys.int_info(bits_per_digit=30, sizeof_digit=4)

在文档中的解释为:

属性解释bits_per_digitnumber of bits held in each digit. Python integers are stored internally in base 2**int_info.bits_per_digitsizeof_digitsize in bytes of the C type used to represent a digit

指的是 Python 以 2 的sys.int_info.bits_per_digit次方为基来表示整数,也就是说它是“2 的sys.int_info.bits_per_digit次方进制”的数。这样的数每一个为都用 C 类中的 4 个字节来存储。

换句话说,每“进 1 位”(即整数值增加2 的sys.int_info.bits_per_digit次方),就需要多分配 4 个字节用以保存某个整数。

因此在sys.getsizeof()的示例中,我们可以看到2**30-1和2**30之间,虽然本身只差了 1,但是所占的字节后者却比前者多了 4。

而sys.float_info的值则是:

>>> sys.float_info

sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

其中各项具体的含义就不在这里继续展开了,感兴趣的同学可以参看文档和《深入理解计算机系统》等讲解组成原理的书。

4. 一个有趣的功能

接下来让我们放松一下。

每次打开 Python 的交互式界面,我们都会看到一个提示符>>>。不知道你有没有想过要把这个东西换成另外的什么呢?

反正我没想过哈哈——至少在文档中看到这两个属性之前,我确实没有想过。哪两个属性呢?

就这俩货:sys.ps1和sys.ps2

所谓“ps”,应当是“prompts”的简写,即“提示符”。

这两个属性中,sys.ps1代表的是一级提示符,也就是进入 Python 交互界面之后就会出现的那一个>>>;而第二个sys.ps2则是二级提示符,是在同一级内容没有输入完,换行之后新行行首的提示符...。当然,两个属性都是字符串。

好了,知道怎么回事儿就好办了。

现在我们就来一个:

>>> sys.ps1 = "justdopython "

justdopython li = [1,2,3]

justdopython li[0]

1

justdopython

提示符已经被改变了,当然,有点长,不大美观哈哈。

咱们换一下:

justdopython sys.ps1 = "ILoveYou: "

ILoveYou: print("你可真是个小机灵鬼儿!")

你可真是个小机灵鬼儿!

ILoveYou:

有点儿意思吧?

注意不要忘了在字符串最后加个空格,否则提示符就会和你输入的内容混杂在一起了,会十分难看的哟~

示例代码:python-100-days

参考资料

Python3 标准库-sys 模块

优惠劵

轩辕御龙

关注

关注

7

点赞

46

收藏

觉得还不错?

一键收藏

知道了

0

评论

Python 标准库之 sys 模块详解

Python sys 模块详解1. 简介“sys”即“system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。2. 常用功能2.1 sys.argv“argv”即“argument value”的简写,是一个列表对象,其中存储的是在命令行调用 Python 脚本时提供的“命令行参...

复制链接

扫一扫

专栏目录

python之sys模块详解_(转)python之os,sys模块详解

weixin_35436076的博客

03-02

276

python之sys模块详解原文:http://www.cnblogs.com/cherishry/p/5725184.htmlsys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧!sys模块的常见函数列表sys.argv: 实现从程序外部向程序传递参数。 sys.exit([arg]): 程序中间的退出,arg=0为正常退出。 sys.getde...

盘点Python编程语言sys库中的7个常用函数

pdcfighting的博客

10-08

542

点击上方“Go语言进阶学习”,进行关注回复“Go语言”即可获赠Python从入门到进阶共10本电子书今日鸡汤青泥何盘盘,百步九折萦岩峦。一、概念这是一个跟 Python 解释器关系密切的...

参与评论

您还未登录,请先

登录

后发表或查看评论

【Python】sys库的介绍及用法

最新发布

qq_53871375的博客

01-27

827

Python的sys库是一种内建模块,可对Python的运行环境进行访问和操作。如果你运行 python myscript.py arg1 arg2,将打印出 ['myscript.py', 'arg1', 'arg2']。sys.modules是一个全局字典,它保存了所有已经导入的Python模块。字典的键是模块的名称,值就是模块对象本身。sys.modules不仅包括由你在代码中导入的模块,还包括Python在启动时自动导入的一些基础模块。以上代码会打印出 Python 搜索模块的路径集。

Python标准库之Sys模块使用详解

12-24

sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分.

处理命令行参数

在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称.

使用sys模块获得脚本的参数

复制代码 代码如下:

print “script name is”, sys.argv[0]        # 使用sys.argv[0]采集脚本名称

if len(sys.argv) > 1:

    print “there are”, len(sys.argv)-1, “arguments:”  # 使用len(sys.argv)-1采集参数个数-1为减去[0]脚本名称

python标准库OS模块详解

12-20

python标准库OS模块简介

os就是“operating system”的缩写,顾名思义,os模块提供的就是各种 Python 程序与操作系统进行交互的接口。通过使用os模块,一方面可以方便地与操作系统进行交互,另一方面页可以极大增强代码的可移植性。如果该模块中相关功能出错,会抛出OSError异常或其子类异常。

注意

如果是读写文件的话,建议使用内置函数open();

如果是路径相关的操作,建议使用os的子模块os.path;

如果要逐行读取多个文件,建议使用fileinput模块;

要创建临时文件或路径,建议使用tempfile模块;

要进行更高级的文件和路径操作则应当使用shuti

Python标准库json模块和pickle模块使用详解

09-17

主要介绍了Python标准库json模块和pickle模块使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Python sys模块常见函数

Liang_xj的博客

07-25

4713

1、sys.argv: 实现从程序外部向程序传递参数。

2、sys.exit([arg]): 程序中间的退出,arg=0为正常退出。

3、sys.getdefaultencoding(): 获取系统当前编码,一般默认为ascii。

4、sys.setdefaultencoding(): 设置系统默认编码,执行dir(sys)时不会看到这个方法,在解释器中执行不通过,可以先执行reload(s...

python——sys模块

记录并分享学习安全的知识点..

02-10

4303

一、概述

sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分。

二、具体使用方法

(一)sys.argv——获取当前正在执行的命令行参数的参数列表(list)

import sys

print (sys.argv[0]) #当前程序名

print (sys.argv[1]) #第一个参数

print (sys.argv[2]) #第二个参数

print (sys.argv[3]) #第三个参数

a = len(sys.argv)-1 #参数个数

print (f'参数个数:

第十二章 sys模块

qq_42226855的博客

06-19

1542

当编写Python 代码时,通常都会得到一个包含Python 代码的以.py 为扩展名的文件。要运行编写的代码,就需要使用Python 解释器去执行.py 文件。因此,Python 解释器就是用来执行Python 代码的一种工具。常见的Python 解释器有以下几种:CPython:Python 的官方解释器。当我们从Python 官方网站下载并安装好Python 后,就直接获得了CPython 解释器,该解释器是使用C 语言开发的,所以叫CPython。

Python sys模块

qq_36594703的博客

05-18

1391

sys” 即 “system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。

Python 常用基础模块(四):sys模块

Amo Xiang的博客

07-04

4905

sys 模块提供访问Python 解释器使用或维护的属性,以及与Python 解释器进行交互的方法。简单来讲,sys 模块负责程序与Python 解释器的交互,并提供了一系列的属性和方法,用于操控Python 运行时的环境。......

100天精通Python(基础篇)——第29天:标准库sys常用函数、方法(基础+代码实战)

努力让自己发光,对的人才能迎着光而来

03-15

3万+

一、sys作用

二、常用变量

sys.version

sys.maxsize

sys.maxunicode

sys.path

sys.platform

sys.argv

sys.executable

sys.byteorder

sys.version_info

sys.api_version

sys.stdin/sys

python中的sys模块函数

csdn_sr的博客

07-14

1364

Sys模块

sys模块常用函数和类

weixin_34195546的博客

01-02

317

函数和类使用项目数

1.argv()

用在(13206)个项目中

2.exit()

用在(11103)个项目中

3.version_info()

用在(4377)个项目中

4.path()

用在(4313)个项目中

5.stdout()

用在(4004)个项目中

6.stderr()

用在(3630)个...

python中的sys模块

d8958的博客

06-10

327

python中的sys模块

python之sys模块详解

热门推荐

wu_zhiyuan的博客

05-12

3万+

前言

sys模块是与python解释器交互的一个接口。sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分。

处理命令行参数

在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称。

sys.argv[0] 表示程序自身

sys.argv[1] 表示程序的第一个参数

sys.argv[2] 表示程序的第二个参数

可以做个测试,如下图:

sys.exit(n) 退出程序,正常退出时exit(0)

#!/usr/bin/env python

# -

python系统模块:sys全解

微小冷的学习笔记

12-07

6457

sys模块

命令行传参

argv和orig_argv可以起到传递命令行参数的作用。例如新建python文件testArgv.py:

import sys

print(sys.argv)

print(sys.orig_argv)

保存之后,在命令行输入

>python testArgv.py ab cde fg

['testArgv.py', 'ab', 'cde', 'fg']

['python', 'testArgv.py', 'ab', 'cde', 'fg']

>python testA

fastdfs-client-java-1.28

05-12

FastDFS是一款开源的分布式文件系统,它提供高容量、高性能和高可靠性的文件存储服务。为了方便Java开发人员使用FastDFS,开发者推出了fastdfs-client-java-1.28。这是一个Java客户端,通过它可以方便地访问FastDFS分布式文件系统,实现文件上传、下载、删除等操作。

fastdfs-client-java-1.28的主要功能包括以下几个方面:

1. 支持文件上传和下载。可以通过该客户端上传文件到FastDFS分布式文件系统,同时也可以下载文件到本地。

2. 支持文件元数据的读取和设置。可以读取和设置文件的元数据,例如文件名、大小、创建时间、修改时间等等。

3. 支持文件的删除和修改。可以通过该客户端执行文件的删除和修改操作。

4. 支持多线程操作。该客户端支持多线程上传和下载文件,可以有效提高文件的上传和下载速度。

5. 支持负载均衡。FastDFS分布式文件系统是一个集群系统,我们可以通过fastdfs-client-java-1.28实现负载均衡,提高文件上传和下载的效率。

总之,fastdfs-client-java-1.28是一个非常实用的Java客户端,可以大大简化Java开发人员与FastDFS分布式文件系统的交互。如果您需要使用FastDFS分布式文件系统,强烈建议使用fastdfs-client-java-1.28,它将会是您的好帮手。

“相关推荐”对你有帮助么?

非常没帮助

没帮助

一般

有帮助

非常有帮助

提交

轩辕御龙

CSDN认证博客专家

CSDN认证企业博客

码龄8年

暂无认证

45

原创

6万+

周排名

120万+

总排名

9万+

访问

等级

1213

积分

63

粉丝

214

获赞

37

评论

493

收藏

私信

关注

热门文章

“常数变易法”有效的原理

54647

Flutter 启动时 gradle 的错误

8752

Python 标准库之 sys 模块详解

6486

Python 小技之繁花曲线

5332

你的代码长啥样?

2915

分类专栏

工具

4篇

Python

16篇

Flutter

1篇

移动开发

1篇

汇编语言

2篇

计算机基础知识

22篇

C语言

1篇

阅读

18篇

轩辕诗集

个人网站

2篇

数学之美

1篇

深度学习

3篇

最新评论

“常数变易法”有效的原理

2301_81837885:

哦哦没事了 我懂了 太牛了啊啊啊醍醐灌顶

“常数变易法”有效的原理

2301_81837885:

所以这不是用另一种方法证明了(9)式吗,感觉还是没讲清常数变易法原理

“常数变易法”有效的原理

heyhhhh:

先辈太聪明,不知道咋想出来的,看完有点理解但没全懂

“常数变易法”有效的原理

MOW158:

老哥确实让我悟了,谢谢

Python 小技之繁花曲线

shumonulir:

这个可以加时间进去吗?就经历t的繁花曲线

您愿意向朋友推荐“博客详情页”吗?

强烈不推荐

不推荐

一般般

推荐

强烈推荐

提交

最新文章

Python一时爽,一直Python一直爽

再谈Python的引用和变量

你的代码长啥样?

2020年16篇

2019年28篇

2018年1篇

目录

目录

分类专栏

工具

4篇

Python

16篇

Flutter

1篇

移动开发

1篇

汇编语言

2篇

计算机基础知识

22篇

C语言

1篇

阅读

18篇

轩辕诗集

个人网站

2篇

数学之美

1篇

深度学习

3篇

目录

评论

被折叠的  条评论

为什么被折叠?

到【灌水乐园】发言

查看更多评论

添加红包

祝福语

请填写红包祝福语或标题

红包数量

红包个数最小为10个

红包总金额

红包金额最低5元

余额支付

当前余额3.43元

前往充值 >

需支付:10.00元

取消

确定

下一步

知道了

成就一亿技术人!

领取后你会自动成为博主和红包主的粉丝

规则

hope_wisdom 发出的红包

实付元

使用余额支付

点击重新获取

扫码支付

钱包余额

0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值

sys — System-specific parameters and functions — Python 3.12.2 documentation

sys — System-specific parameters and functions — Python 3.12.2 documentation

Theme

Auto

Light

Dark

Previous topic

Python Runtime Services

Next topic

sys.monitoring — Execution event monitoring

This Page

Report a Bug

Show Source

Navigation

index

modules |

next |

previous |

Python »

3.12.2 Documentation »

The Python Standard Library »

Python Runtime Services »

sys — System-specific parameters and functions

|

Theme

Auto

Light

Dark

|

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.

New in version 3.2.

Changed in version 3.8: Default flags became an empty string (m flag for pymalloc has been

removed).

Availability: Unix.

sys.addaudithook(hook)¶

Append the callable hook to the list of active auditing hooks for the

current (sub)interpreter.

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. Native hooks added by PySys_AddAuditHook() are

called first, followed by hooks added in the current (sub)interpreter. Hooks

can then log the event, raise an exception to abort the operation,

or terminate the process entirely.

Note that audit hooks are primarily for collecting information about internal

or otherwise unobservable actions, whether by Python or libraries written in

Python. They are not suitable for implementing a “sandbox”. In particular,

malicious code can trivially disable or bypass hooks added using this

function. At a minimum, any security-sensitive hooks must be added using the

C API PySys_AddAuditHook() before initialising the runtime, and any

modules allowing arbitrary memory modification (such as ctypes) should

be completely removed or closely monitored.

Calling sys.addaudithook() will itself raise an auditing event

named sys.addaudithook with no arguments. If any

existing hooks raise an exception derived from RuntimeError, the

new hook will not be added and the exception suppressed. 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.

New in version 3.8.

Changed in version 3.8.1: Exceptions derived from Exception but not RuntimeError

are no longer suppressed.

CPython implementation detail: 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. Otherwise, trace functions will skip the hook.

sys.argv¶

The list of command line arguments passed to a Python script. argv[0] is the

script name (it is operating system dependent whether this is a full pathname or

not). If the command was executed using the -c command line option to

the interpreter, argv[0] is set to the string '-c'. If no script name

was passed to the Python interpreter, argv[0] is the empty string.

To loop over the standard input, or the list of files given on the

command line, see the fileinput module.

See also sys.orig_argv.

Note

On Unix, command line arguments are passed by bytes from OS. Python decodes

them with filesystem encoding and “surrogateescape” error handler.

When you need original bytes, you can get it by

[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. The

number and types of arguments for a given event are considered a

public and stable API and should not be modified between releases.

For example, one auditing event is named os.chdir. This event has

one argument called path that will contain the requested new

working directory.

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() or

PySys_AddAuditHook() functions.

The native equivalent of this function is PySys_Audit(). Using the

native function is preferred when possible.

See the audit events table for all events raised by

CPython.

New in version 3.8.

sys.base_exec_prefix¶

Set during Python startup, before site.py is run, to the same value as

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 of

prefix and exec_prefix will be changed to point to the

virtual environment, whereas base_prefix and

base_exec_prefix will remain pointing to the base Python

installation (the one which the virtual environment was created from).

New in version 3.3.

sys.base_prefix¶

Set during Python startup, before site.py is run, to the same value as

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 of prefix and exec_prefix will be changed to

point to the virtual environment, whereas base_prefix and

base_exec_prefix will remain pointing to the base Python

installation (the one which the virtual environment was created from).

New in version 3.3.

sys.byteorder¶

An indicator of the native byte order. This will have the value 'big' on

big-endian (most-significant byte first) platforms, and 'little' on

little-endian (least-significant byte first) platforms.

sys.builtin_module_names¶

A tuple of strings containing the names of all modules that are compiled into this

Python interpreter. (This information is not available in any other way —

modules.keys() only lists the imported modules.)

See also the sys.stdlib_module_names list.

sys.call_tracing(func, args)¶

Call func(*args), while tracing is enabled. The tracing state is saved,

and restored afterwards. This is intended to be called from a debugger from

a checkpoint, to recursively debug or profile some other code.

Tracing is suspended while calling a tracing function set by

settrace() or setprofile() to avoid infinite recursion.

call_tracing() enables explicit recursion of the tracing function.

sys.copyright¶

A string containing the copyright pertaining to the Python interpreter.

sys._clear_type_cache()¶

Clear the internal type cache. The type cache is used to speed up attribute

and method lookups. Use the function only to drop unnecessary references

during reference leak debugging.

This function should be used for internal and specialized purposes only.

sys._current_frames()¶

Return a dictionary mapping each thread’s identifier to the topmost stack frame

currently active in that thread at the time the function is called. Note that

functions in the traceback module can build the call stack given such a

frame.

This is most useful for debugging deadlock: this function does not require the

deadlocked threads’ cooperation, and such threads’ call stacks are frozen for as

long as they remain deadlocked. The frame returned for a non-deadlocked thread

may bear no relationship to that thread’s current activity by the time calling

code examines the frame.

This function should be used for internal and specialized purposes only.

Raises an auditing event sys._current_frames with no arguments.

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.

Changed in version 3.12: Each value in the dictionary is now a single exception instance, rather

than a 3-tuple as returned from sys.exc_info().

sys.breakpointhook()¶

This hook function is called by built-in 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.

The signature of this function is dependent on what it calls. For example,

the default binding (e.g. pdb.set_trace()) expects no arguments, but

you might bind it to a function that expects additional arguments

(positional and/or keyword). The built-in breakpoint() function passes

its *args and **kws straight through. Whatever

breakpointhooks() returns is returned from breakpoint().

The default implementation first consults the environment variable

PYTHONBREAKPOINT. If that is set to "0" then this function

returns immediately; i.e. it is a no-op. If the environment variable is

not set, or is set to the empty string, pdb.set_trace() is called.

Otherwise this variable should name a function to run, using Python’s

dotted-import nomenclature, e.g. package.subpackage.module.function.

In this case, package.subpackage.module would be imported and the

resulting module must have a callable named function(). This is run,

passing in *args and **kws, and whatever function() returns,

sys.breakpointhook() returns to the built-in breakpoint()

function.

Note that if anything goes wrong while importing the callable named by

PYTHONBREAKPOINT, a RuntimeWarning is reported and the

breakpoint is ignored.

Also note that if sys.breakpointhook() is overridden programmatically,

PYTHONBREAKPOINT is not consulted.

New in version 3.7.

sys._debugmallocstats()¶

Print low-level information to stderr about the state of CPython’s memory

allocator.

If Python is built in debug mode (configure

--with-pydebug option), it also performs some expensive

internal consistency checks.

New in version 3.3.

CPython implementation detail: This function is specific to CPython. The exact output format is not

defined here, and may change.

sys.dllhandle¶

Integer specifying the handle of the Python DLL.

Availability: Windows.

sys.displayhook(value)¶

If value is not None, this function prints repr(value) to

sys.stdout, and saves value in builtins._. If repr(value) is

not encodable to sys.stdout.encoding with sys.stdout.errors error

handler (which is probably 'strict'), encode it to

sys.stdout.encoding with 'backslashreplace' error handler.

sys.displayhook is called on the result of evaluating an expression

entered in an interactive Python session. The display of these values can be

customized by assigning another one-argument function to 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._ = value

Changed in version 3.2: Use 'backslashreplace' error handler on UnicodeEncodeError.

sys.dont_write_bytecode¶

If this is true, Python won’t try to write .pyc files on the

import of source modules. This value is initially set to True or

False depending on the -B command line option and the

PYTHONDONTWRITEBYTECODE environment variable, but you can set it

yourself to control bytecode file generation.

sys._emscripten_info¶

A named tuple holding information about the environment on the

wasm32-emscripten platform. The named tuple is provisional and may change

in the future.

_emscripten_info.emscripten_version¶

Emscripten version as tuple of ints (major, minor, micro), e.g. (3, 1, 8).

_emscripten_info.runtime¶

Runtime string, e.g. browser user agent, 'Node.js v14.18.2', or 'UNKNOWN'.

_emscripten_info.pthreads¶

True if Python is compiled with Emscripten pthreads support.

_emscripten_info.shared_memory¶

True if Python is compiled with shared memory support.

Availability: Emscripten.

New in version 3.11.

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. Any __pycache__ directories in the source code tree will be ignored

and new .pyc files written within the pycache prefix. 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.

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 the

PYTHONPYCACHEPREFIX environment variable (command-line takes

precedence). If neither are set, it is None.

New in version 3.8.

sys.excepthook(type, value, traceback)¶

This function prints out a given traceback and exception to sys.stderr.

When an exception other than SystemExit is raised and uncaught, the interpreter calls

sys.excepthook with three arguments, the exception class, exception

instance, and a traceback object. In an interactive session this happens just

before control is returned to the prompt; in a Python program this happens just

before the program exits. The handling of such top-level exceptions can be

customized by assigning another three-argument function to sys.excepthook.

Raise an auditing event sys.excepthook with arguments hook,

type, value, traceback when an uncaught exception occurs.

If no hook has been set, hook may be None. If any hook raises

an exception derived from RuntimeError the call to the hook will

be suppressed. Otherwise, the audit hook exception will be reported as

unraisable and sys.excepthook will be called.

See also

The sys.unraisablehook() function handles unraisable exceptions

and the threading.excepthook() function handles exception raised

by threading.Thread.run().

sys.__breakpointhook__¶

sys.__displayhook__¶

sys.__excepthook__¶

sys.__unraisablehook__¶

These objects contain the original values of breakpointhook,

displayhook, excepthook, and unraisablehook at the start of the

program. They are saved so that breakpointhook, displayhook and

excepthook, unraisablehook can be restored in case they happen to

get replaced with broken or alternative objects.

New in version 3.7: __breakpointhook__

New in version 3.8: __unraisablehook__

sys.exception()¶

This function, when called while an exception handler is executing (such as

an except or except* clause), returns the exception instance that

was caught by this handler. When exception handlers are nested within one

another, only the exception handled by the innermost handler is accessible.

If no exception handler is executing, this function returns None.

New in version 3.11.

sys.exc_info()¶

This function returns the old-style representation of the handled

exception. If an exception e is currently handled (so

exception() would return e), exc_info() returns the

tuple (type(e), e, e.__traceback__).

That is, a tuple containing the type of the exception (a subclass of

BaseException), the exception itself, and a traceback

object which typically encapsulates the call

stack at the point where the exception last occurred.

If no exception is being handled anywhere on the stack, this function

return a tuple containing three None values.

Changed in version 3.11: The type and traceback fields are now derived from the value

(the exception instance), so when an exception is modified while it is

being handled, the changes are reflected in the results of subsequent

calls to exc_info().

sys.exec_prefix¶

A string giving the site-specific directory prefix where the platform-dependent

Python files are installed; by default, this is also '/usr/local'. This can

be set at build time with the --exec-prefix argument to the

configure script. Specifically, all configuration files (e.g. the

pyconfig.h header file) are installed in the directory

exec_prefix/lib/pythonX.Y/config, and shared library modules are

installed in exec_prefix/lib/pythonX.Y/lib-dynload, where X.Y

is the version number of Python, for example 3.2.

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, via

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. If Python is unable to retrieve

the real path to its executable, sys.executable will be an empty string

or None.

sys.exit([arg])¶

Raise a SystemExit exception, signaling an intention to exit the interpreter.

The optional argument arg can be an integer giving the exit status

(defaulting to zero), or another type of object. If it is an integer, zero

is considered “successful termination” and any nonzero value is considered

“abnormal termination” by shells and the like. Most systems require it to be

in the range 0–127, and produce undefined results otherwise. Some systems

have a convention for assigning specific meanings to specific exit codes, but

these are generally underdeveloped; Unix programs generally use 2 for command

line syntax errors and 1 for all other kind of errors. If another type of

object is passed, None is equivalent to passing zero, and any other

object is printed to stderr and results in an exit code of 1. In

particular, sys.exit("some error message") is a quick way to exit a

program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit

the process when called from the main thread, and the exception is not

intercepted. Cleanup actions specified by finally clauses of try statements

are honored, and it is possible to intercept the exit attempt at an outer level.

Changed in version 3.6: If an error occurs in the cleanup after the Python interpreter

has caught SystemExit (such as an error flushing buffered data

in the standard streams), the exit status is changed to 120.

sys.flags¶

The named tuple flags exposes the status of command line

flags. The attributes are read only.

flags.debug¶

-d

flags.inspect¶

-i

flags.interactive¶

-i

flags.isolated¶

-I

flags.optimize¶

-O or -OO

flags.dont_write_bytecode¶

-B

flags.no_user_site¶

-s

flags.no_site¶

-S

flags.ignore_environment¶

-E

flags.verbose¶

-v

flags.bytes_warning¶

-b

flags.quiet¶

-q

flags.hash_randomization¶

-R

flags.dev_mode¶

-X dev (Python Development Mode)

flags.utf8_mode¶

-X utf8

flags.safe_path¶

-P

flags.int_max_str_digits¶

-X int_max_str_digits

(integer string conversion length limitation)

flags.warn_default_encoding¶

-X warn_default_encoding

Changed in version 3.2: Added quiet attribute for the new -q flag.

New in version 3.2.3: The hash_randomization attribute.

Changed in version 3.3: Removed obsolete division_warning attribute.

Changed in version 3.4: Added isolated attribute for -I isolated flag.

Changed in version 3.7: Added the dev_mode attribute for the new Python Development

Mode and the utf8_mode attribute for the new -X

utf8 flag.

Changed in version 3.10: Added warn_default_encoding attribute for -X warn_default_encoding flag.

Changed in version 3.11: Added the safe_path attribute for -P option.

Changed in version 3.11: Added the int_max_str_digits attribute.

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 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.

Attributes of the float_info named tuple¶

attribute

float.h macro

explanation

float_info.epsilon¶

DBL_EPSILON

difference between 1.0 and the least value greater than 1.0 that is

representable as a float.

See also math.ulp().

float_info.dig¶

DBL_DIG

The maximum number of decimal digits that can be faithfully

represented in a float; see below.

float_info.mant_dig¶

DBL_MANT_DIG

Float precision: the number of base-radix digits in the

significand of a float.

float_info.max¶

DBL_MAX

The maximum representable positive finite float.

float_info.max_exp¶

DBL_MAX_EXP

The maximum integer e such that radix**(e-1) is a representable

finite float.

float_info.max_10_exp¶

DBL_MAX_10_EXP

The maximum integer e such that 10**e is in the range of

representable finite floats.

float_info.min¶

DBL_MIN

The minimum representable positive normalized float.

Use math.ulp(0.0) to get the smallest positive

denormalized representable float.

float_info.min_exp¶

DBL_MIN_EXP

The minimum integer e such that radix**(e-1) is a normalized

float.

float_info.min_10_exp¶

DBL_MIN_10_EXP

The minimum integer e such that 10**e is a normalized float.

float_info.radix¶

FLT_RADIX

The radix of exponent representation.

float_info.rounds¶

FLT_ROUNDS

An integer representing the rounding mode for floating-point arithmetic.

This reflects the value of the system FLT_ROUNDS macro

at interpreter startup time:

-1: indeterminable

0: toward zero

1: to nearest

2: toward positive infinity

3: toward negative infinity

All other values for FLT_ROUNDS characterize

implementation-defined rounding behavior.

The attribute sys.float_info.dig needs further explanation. If

s is any string representing a decimal number with at most

sys.float_info.dig significant digits, then converting s to a

float and back again will recover a string representing the same decimal

value:

>>> import sys

>>> sys.float_info.dig

15

>>> s = '3.14159265358979' # decimal string with 15 significant digits

>>> format(float(s), '.15g') # convert to float and back -> same value

'3.14159265358979'

But for strings with more than sys.float_info.dig significant digits,

this isn’t always true:

>>> s = '9876543211234567' # 16 significant digits is too many!

>>> format(float(s), '.16g') # conversion changes value

'9876543211234568'

sys.float_repr_style¶

A string indicating how the repr() function behaves for

floats. If the string has value 'short' then for a finite

float x, repr(x) aims to produce a short string with the

property that float(repr(x)) == x. This is the usual behaviour

in Python 3.1 and later. Otherwise, float_repr_style has value

'legacy' and repr(x) behaves in the same way as it did in

versions of Python prior to 3.1.

New in version 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() and gc.collect() to get more

predictable results.

If a Python build or implementation cannot reasonably compute this

information, getallocatedblocks() is allowed to return 0 instead.

New in version 3.4.

sys.getunicodeinternedsize()¶

Return the number of unicode objects that have been interned.

New in version 3.12.

sys.getandroidapilevel()¶

Return the build time API version of Android as an integer.

Availability: Android.

New in version 3.7.

sys.getdefaultencoding()¶

Return the name of the current default string encoding used by the Unicode

implementation.

sys.getdlopenflags()¶

Return the current value of the flags that are used for

dlopen() calls. Symbolic names for the flag values can be

found in the os module (RTLD_xxx constants, e.g.

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. The filesystem error handler is returned from

getfilesystemencodeerrors().

For best compatibility, str should be used for filenames in all cases,

although representing filenames as bytes is also supported. Functions

accepting or returning filenames should support either str or bytes and

internally convert to the system’s preferred representation.

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 the PyConfig_Read() function: see

filesystem_encoding and

filesystem_errors members of PyConfig.

Changed in version 3.2: getfilesystemencoding() result cannot be None anymore.

Changed in version 3.6: Windows is no longer guaranteed to return 'mbcs'. See PEP 529

and _enablelegacywindowsfsencoding() for more information.

Changed in version 3.7: Return 'utf-8' if the Python UTF-8 Mode is

enabled.

sys.getfilesystemencodeerrors()¶

Get the filesystem error handler: the error handler used with the filesystem encoding to convert between Unicode

filenames and bytes filenames. The filesystem encoding is returned from

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 the PyConfig_Read() function: see

filesystem_encoding and

filesystem_errors members of PyConfig.

New in version 3.6.

sys.get_int_max_str_digits()¶

Returns the current value for the integer string conversion length

limitation. See also set_int_max_str_digits().

New in version 3.11.

sys.getrefcount(object)¶

Return the reference count of the object. The count returned is generally one

higher than you might expect, because it includes the (temporary) reference as

an argument to getrefcount().

Note that the returned value may not actually reflect how many

references to the object are actually held. For example, some

objects are “immortal” and have a very high refcount that does not

reflect the actual number of references. Consequently, do not rely

on the returned value to be accurate, other than a value of 0 or 1.

Changed in version 3.12: Immortal objects have very large refcounts that do not match

the actual number of references to the object.

sys.getrecursionlimit()¶

Return the current value of the recursion limit, the maximum depth of the Python

interpreter stack. This limit prevents infinite recursion from causing an

overflow of the C stack and crashing Python. It can be set by

setrecursionlimit().

sys.getsizeof(object[, default])¶

Return the size of an object in bytes. The object can be any type of

object. All built-in objects will return correct results, but this

does not have to hold true for third-party extensions as it is implementation

specific.

Only the memory consumption directly attributed to the object is

accounted for, not the memory consumption of objects it refers to.

If given, default will be returned if the object does not provide means to

retrieve the size. Otherwise a TypeError will be raised.

getsizeof() calls the object’s __sizeof__ method and adds an

additional garbage collector overhead if the object is managed by the garbage

collector.

See recursive sizeof recipe

for an example of using getsizeof() recursively to find the size of

containers and all their contents.

sys.getswitchinterval()¶

Return the interpreter’s “thread switch interval”; see

setswitchinterval().

New in version 3.2.

sys._getframe([depth])¶

Return a frame object from the call stack. If optional integer depth is

given, return the frame object that many calls below the top of the stack. If

that is deeper than the call stack, ValueError is raised. The default

for depth is zero, returning the frame at the top of the call stack.

Raises an auditing event sys._getframe with argument frame.

CPython implementation detail: This function should be used for internal and specialized purposes only.

It is not guaranteed to exist in all implementations of Python.

sys._getframemodulename([depth])¶

Return the name of a module from the call stack. If optional integer depth

is given, return the module that many calls below the top of the stack. If

that is deeper than the call stack, or if the module is unidentifiable,

None is returned. The default for depth is zero, returning the

module at the top of the call stack.

Raises an auditing event sys._getframemodulename with argument depth.

CPython implementation detail: This function should be used for internal and specialized purposes only.

It is not guaranteed to exist in all implementations of Python.

sys.getprofile()¶

Get the profiler function as set by setprofile().

sys.gettrace()¶

Get the trace function as set by settrace().

CPython implementation detail: The gettrace() function is intended only for implementing debuggers,

profilers, coverage tools and the like. Its behavior is part of the

implementation platform, rather than part of the language definition, and

thus may not be available in all Python implementations.

sys.getwindowsversion()¶

Return a named tuple describing the Windows version

currently running. The named elements are major, minor,

build, platform, service_pack, service_pack_minor,

service_pack_major, suite_mask, product_type and

platform_version. service_pack contains a string,

platform_version a 3-tuple and all other values are

integers. The components can also be accessed by name, so

sys.getwindowsversion()[0] is equivalent to

sys.getwindowsversion().major. For compatibility with prior

versions, only the first 5 elements are retrievable by indexing.

platform will be 2 (VER_PLATFORM_WIN32_NT).

product_type may be one of the following values:

Constant

Meaning

1 (VER_NT_WORKSTATION)

The system is a workstation.

2 (VER_NT_DOMAIN_CONTROLLER)

The system is a domain

controller.

3 (VER_NT_SERVER)

The system is a server, but not

a domain controller.

This function wraps the Win32 GetVersionEx() function; see the

Microsoft documentation on OSVERSIONINFOEX() for more information

about these fields.

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. Please use platform module for achieving accurate

OS version.

Availability: Windows.

Changed in version 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: Added 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 either None 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: 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.

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.

hash_info.width¶

The width in bits used for hash values

hash_info.modulus¶

The prime modulus P used for numeric hash scheme

hash_info.inf¶

The hash value returned for a positive infinity

hash_info.nan¶

(This attribute is no longer used)

hash_info.imag¶

The multiplier used for the imaginary part of a complex number

hash_info.algorithm¶

The name of the algorithm for hashing of str, bytes, and memoryview

hash_info.hash_bits¶

The internal output size of the hash algorithm

hash_info.seed_bits¶

The size of the seed key of the hash algorithm

New in version 3.2.

Changed in version 3.4: Added algorithm, hash_bits and seed_bits

sys.hexversion¶

The version number encoded as a single integer. This is guaranteed to increase

with each version, including proper support for non-production releases. For

example, to test that the Python interpreter is at least version 1.5.2, use:

if sys.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-in hex() function. The

named tuple sys.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.

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, which sys.version_info represents. For

example, for PyPy 1.8 sys.implementation.version might be

sys.version_info(1, 8, 0, 'final', 0), whereas sys.version_info

would be sys.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. If

cache_tag is set to None, it indicates that module caching should

be disabled.

sys.implementation may 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.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.

Note

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.

int_info.bits_per_digit¶

The number of bits held in each digit.

Python integers are stored internally in base 2**int_info.bits_per_digit.

int_info.sizeof_digit¶

The size in bytes of the C type used to represent a digit.

int_info.default_max_str_digits¶

The default value for sys.get_int_max_str_digits()

when it is not otherwise explicitly configured.

int_info.str_digits_check_threshold¶

The minimum non-zero value for sys.set_int_max_str_digits(),

PYTHONINTMAXSTRDIGITS, or -X int_max_str_digits.

New in version 3.1.

Changed in version 3.11: Added default_max_str_digits and

str_digits_check_threshold.

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 PYTHONSTARTUP file is

read, so that you can set this hook there. The site module

sets this.

Raises an auditing event

cpython.run_interactivehook with the hook object as the argument when

the hook is called on startup.

New in version 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 True if the Python interpreter is

shutting down, False otherwise.

New in version 3.5.

sys.last_exc¶

This variable is not always defined; it is set to the exception instance

when an exception is not handled and the interpreter prints an error message

and a stack traceback. Its 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; see pdb

module for more information.)

New in version 3.12.

sys.last_type¶

sys.last_value¶

sys.last_traceback¶

These three variables are deprecated; use sys.last_exc instead.

They hold the legacy representation of sys.last_exc, as returned

from exc_info() above.

sys.maxsize¶

An integer giving the maximum value a variable of type Py_ssize_t can

take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a

64-bit platform.

sys.maxunicode¶

An integer giving the value of the largest Unicode code point,

i.e. 1114111 (0x10FFFF in hexadecimal).

Changed in version 3.3: Before PEP 393, sys.maxunicode used to be either 0xFFFF

or 0x10FFFF, 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. By default, it holds entries

that implement Python’s default import semantics. The

find_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, or None if the module cannot be found.

See also

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.

Changed in version 3.4: Module specs were introduced in Python 3.4, by

PEP 451.

Changed in version 3.12: Removed the fallback that looked for a find_module() method

if a meta_path entry didn’t have a

find_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. If

you want to iterate over this global dictionary always use

sys.modules.copy() or tuple(sys.modules) to avoid exceptions as its

size may change during iteration as a side effect of code or activity in

other threads.

sys.orig_argv¶

The list of the original command line arguments passed to the Python

executable.

The elements of sys.orig_argv are the arguments to the Python interpreter,

while the elements of sys.argv are the arguments to the user’s program.

Arguments consumed by the interpreter itself will be present in sys.orig_argv

and missing from sys.argv.

New in version 3.10.

sys.path¶

A list of strings that specifies the search path for modules. Initialized from

the environment variable PYTHONPATH, plus an installation-dependent

default.

By default, as initialized upon program startup, a potentially unsafe path

is prepended to sys.path (before the entries inserted as a result

of PYTHONPATH):

python -m module command line: prepend the current working

directory.

python script.py command line: prepend the script’s directory.

If it’s a symbolic link, resolve symbolic links.

python -c code and python (REPL) command lines: prepend an empty

string, which means the current working directory.

To not prepend this potentially unsafe path, use the -P command

line option or the PYTHONSAFEPATH environment variable.

A program is free to modify this list for its own purposes. Only strings

should be added to sys.path; all other data types are

ignored during import.

See also

Module site This describes how to use .pth files to

extend sys.path.

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_hooks and the values are

the finders that are found. If a path is a valid file system path but no

finder is found on sys.path_hooks then None is

stored.

Originally specified in PEP 302.

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 -s with the first part of the version as returned by

uname -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 value

AIX

'aix'

Emscripten

'emscripten'

Linux

'linux'

WASI

'wasi'

Windows

'win32'

Windows/Cygwin

'cygwin'

macOS

'darwin'

Changed in version 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 startswith idiom presented above.

Changed in version 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 startswith idiom presented above.

See also

os.name has a coarser granularity. os.uname() gives

system-dependent version information.

The platform module provides detailed checks for the

system’s identity.

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 following sys.path

paths (where X.Y is the Python major.minor version):

/usr/lib64/pythonX.Y/:

Standard library (like os.py of the os module)

/usr/lib64/pythonX.Y/lib-dynload/:

C extension modules of the standard library (like the errno module,

the exact filename is platform specific)

/usr/lib/pythonX.Y/site-packages/ (always use lib, not

sys.platlibdir): Third-party modules

/usr/lib64/pythonX.Y/site-packages/:

C extension modules of third-party packages

New in version 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

/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, via base_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.

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 as

sys.setdlopenflags(0). To share symbols across extension modules, call as

sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag values

can be found in the os module (RTLD_xxx constants, e.g.

os.RTLD_LAZY).

Availability: Unix.

sys.set_int_max_str_digits(maxdigits)¶

Set the integer string conversion length limitation used by this interpreter. See also

get_int_max_str_digits().

New in version 3.11.

sys.setprofile(profilefunc)¶

Set the system’s profile function, which allows you to implement a Python source

code profiler in Python. See chapter The Python Profilers for more information on the

Python profiler. 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). 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. Error in the profile

function will cause itself unset.

Note

The same tracing mechanism is used for setprofile() as settrace().

To trace calls with setprofile() inside a tracing function

(e.g. in a debugger breakpoint), see call_tracing().

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.

The events have the following meaning:

'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 None

if 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.

Raises an auditing event sys.setprofile with no arguments.

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

RecursionError exception is raised.

Changed in version 3.5.1: A RecursionError exception is now raised if the new limit is too

low at the current recursion depth.

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. 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.

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 use 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, or None if the scope shouldn’t be

traced.

The local trace function should return a reference to itself, or to another

function which would then be used as the local trace function for the scope.

If there is any error occurred in the trace function, it will be unset, just

like settrace(None) is called.

Note

Tracing is disabled while calling the trace function (e.g. a function set by

settrace()). For recursive tracing see call_tracing().

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 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. See

Objects/lnotab_notes.txt for a detailed explanation of how this

works.

Per-line events may be disabled for a frame by setting

f_trace_lines to False 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 None

if 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 dis for

opcode details). The local trace function is called; arg is

None; the return value specifies the new local trace function.

Per-opcode events are not emitted by default: they must be explicitly

requested by setting f_trace_opcodes to True on 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 = 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. 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 returns None to disable

itself immediately on each frame).

For more information on code and frame objects, refer to The standard type hierarchy.

Raises an auditing event sys.settrace with 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.

Changed in version 3.7: 'opcode' event type added; f_trace_lines and

f_trace_opcodes attributes added to frames

Changed in version 3.12: 'opcode' event will only be emitted if f_trace_opcodes

of at least one frame has been set to True before settrace()

is called. This behavior will be changed back in 3.13 to be consistent with

previous versions.

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_firstiter with no arguments.

Raises an auditing event sys.set_asyncgen_hooks_finalizer with no arguments.

Two auditing events are raised because the underlying API consists of two

calls, each of which must raise its own event.

New in version 3.6: See PEP 525 for more details, and for a reference example of a

finalizer method see the implementation of

asyncio.Loop.shutdown_asyncgens in

Lib/asyncio/base_events.py

Note

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_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.

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.

New in version 3.7.

Note

This function has been added on a provisional basis (see PEP 411

for details.) Use it only for debugging purposes.

sys.activate_stack_trampoline(backend, /)¶

Activate the stack profiler trampoline backend.

The only supported backend is "perf".

Availability: Linux.

New in version 3.12.

See also

Python support for the Linux perf profiler

https://perf.wiki.kernel.org

sys.deactivate_stack_trampoline()¶

Deactivate the current stack profiler trampoline backend.

If no stack profiler is activated, this function has no effect.

Availability: Linux.

New in version 3.12.

sys.is_stack_trampoline_active()¶

Return True if a stack profiler trampoline is active.

Availability: Linux.

New in version 3.12.

sys._enablelegacywindowsfsencoding()¶

Changes the filesystem encoding and error handler to ‘mbcs’ and

‘replace’ respectively, for consistency with versions of Python prior to

3.6.

This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING

environment variable before launching Python.

See also sys.getfilesystemencoding() and

sys.getfilesystemencodeerrors().

Availability: Windows.

New in version 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());

stdout is used for the output of print() and expression

statements and for the prompts of input();

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 encoding and error handling are is initialized from

PyConfig.stdio_encoding and PyConfig.stdio_errors.

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() returns True) 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 PYTHONIOENCODING environment variable before

starting Python or by using the new -X utf8 command

line option and PYTHONUTF8 environment variable. However,

for the Windows console, this only applies when

PYTHONLEGACYWINDOWSSTDIO is also set.

When interactive, the stdout stream is line-buffered. Otherwise,

it is block-buffered like regular text files. The stderr stream

is line-buffered in both cases. You can make both streams unbuffered

by passing the -u command-line option or setting the

PYTHONUNBUFFERED environment variable.

Changed in version 3.9: Non-interactive stderr 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. For example, to

write bytes to stdout, use sys.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 the buffer attribute.

sys.__stdin__¶

sys.__stdout__¶

sys.__stderr__¶

These objects contain the original values of stdin, stderr and

stdout at the start of the program. 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.

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 and stderr as well as the

original values __stdin__, __stdout__ and __stderr__ can be

None. 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.

All module kinds are listed: pure Python, built-in, frozen and extension

modules. Test modules are excluded.

For packages, only the main package is listed: sub-packages and sub-modules

are not listed. For example, the email package is listed, but the

email.mime sub-package and the email.message sub-module are not

listed.

See also the sys.builtin_module_names list.

New in version 3.10.

sys.thread_info¶

A named tuple holding information about the thread

implementation.

thread_info.name¶

The name of the thread implementation:

"nt": Windows threads

"pthread": POSIX threads

"pthread-stubs": stub POSIX threads

(on WebAssembly platforms without threading support)

"solaris": Solaris threads

thread_info.lock¶

The name of the lock implementation:

"semaphore": a lock uses a semaphore

"mutex+cond": a lock uses a mutex and a condition variable

None if this information is unknown

thread_info.version¶

The name and version of the thread library.

It is a string, or None if this information is unknown.

New in version 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 to 0 or 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: Exception type.

exc_value: Exception value, can be 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 is None.

sys.unraisablehook() can be overridden to control how unraisable

exceptions are handled.

See also

excepthook() which handles uncaught exceptions.

Warning

Storing exc_value using a custom hook can create a reference cycle.

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. Avoid storing object after the custom

hook completes to avoid resurrecting objects.

Raise an auditing event sys.unraisablehook with arguments

hook, unraisable when an exception that cannot be handled occurs.

The unraisable object is the same as what will be passed to the hook.

If no hook has been set, hook may be None.

New in version 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_info and the functions provided by the

platform module.

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'. The version_info value corresponding to the Python version 2.0

is (2, 0, 0, 'final', 0). The components can also be accessed by name,

so sys.version_info[0] is equivalent to sys.version_info.major

and so on.

Changed in version 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.

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

major and minor versions of the running Python interpreter. It is provided in the sys

module for informational purposes; modifying this value has no effect on the

registry keys used by Python.

Availability: Windows.

sys.monitoring

Namespace containing functions and constants for register callbacks

and controlling monitoring events.

See sys.monitoring for details.

sys._xoptions¶

A dictionary of the various implementation-specific flags passed through

the -X command-line option. Option names are either mapped to

their values, if given explicitly, or to 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: This is a CPython-specific way of accessing options passed through

-X. Other implementations may export them through other

means, or not at all.

New in version 3.2.

Citations

[C99]

ISO/IEC 9899:1999. “Programming languages – C.” A public draft of this standard is available at https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.

Previous topic

Python Runtime Services

Next topic

sys.monitoring — Execution event monitoring

This Page

Report a Bug

Show Source

«

Navigation

index

modules |

next |

previous |

Python »

3.12.2 Documentation »

The Python Standard Library »

Python Runtime Services »

sys — System-specific parameters and functions

|

Theme

Auto

Light

Dark

|

© Copyright 2001-2024, Python Software Foundation.

This page is licensed under the Python Software Foundation License Version 2.

Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.

See History and License for more information.

The Python Software Foundation is a non-profit corporation.

Please donate.

Last updated on Mar 06, 2024 (20:51 UTC).

Found a bug?

Created using Sphinx 7.2.6.

Python 中5个必须了解的sys模块的用法 - 知乎

Python 中5个必须了解的sys模块的用法 - 知乎切换模式写文章登录/注册Python 中5个必须了解的sys模块的用法高小虎​可以说 sys 是 python 中的解释器模块, 因为它提供了一些变量和函数,这些变量可被解释器(interpreter)使用,也可由解释器提供,它们之间由此产生交互功能。1. 命令行参数传递给 Python 程序的命令行参数由 sys 模块存储在名为 argv 的列表中。默认情况下,argv 的长度为1,由程序名称组成。假如我写了一个名为 test.py 程序,内容如下:from sys import argv

# 打印 'argv' 中所有参数

for i in range(len(argv)):

print(argv[i])然后我在命令行下运行这个程序:它输出了该程序的名称,如果我在其后面添加几个参数:它会该程序名称和后面所有的参数。2.退出 Python 程序在某些情况下,sys 模块的退出功能可用于终止程序并从程序退出。传递给exit的参数是可选的。例如:import sys

password = input()

if(password == '错误的密码'):

print('密码错误')

sys.exit()

else:

print('欢迎光临')3.设置并获取Python解释器堆栈的深度我们可以通过"setrecursionlimit"功能设置解释器堆栈深度。此限制可防止无限递归导致 C 堆栈溢出和 Python 崩溃。 sys 模块中的"getrecursionlimit"函数返回递归限制的当前值,即 Python 解释器堆栈的最大深度。import sys

# 请不要设置负数或者将值设置的过低

limit = int(input('Python 解释器堆栈的深度应该是多少 '))

sys.setrecursionlimit(limit)

print('堆栈的深度应该是', sys.getrecursionlimit())4.获取解释器版本在Python中,解释器的高级版本具有一些高级功能,较旧版本的解释器可能不支持。在这种情况下,我们必须确定解释器的版本是否可以使用某些较新的功能。 sys.hexversion 可用于查找解释器的版本。import sys

# 检查解释器的版本是否至少为1.5.2

if sys.hexversion >= 0x010502F0:

# 这有些高级的功能

# ...

else:

# 给它个吓人的提示

# ...5.确定系统(OS)版本程序中某些功能的实现可能因平台而异。在 Linux上 运行的代码可能无法在 Windows 上运行,反之亦然。在这种情况下,我们需要根据平台编写单独的代码。为此,我们可以使用 sys.platform 标识主机操作系统。import sys

platform = sys.platform

if platform == 'linux':

# Linux 的代码

print('这是 linux 系统')

elif platform == 'win32':

# Windows 的代码

print('这是 windows 系统')

elif platform == 'darwin':

# macOS 的代码

print('这是苹果系统')发布于 2021-02-04 15:19Python虚拟机Python解释器​赞同 4​​添加评论​分享​喜欢​收藏​申请

Python中的sys模块详解_python sys模块详解-CSDN博客

>

Python中的sys模块详解_python sys模块详解-CSDN博客

Python中的sys模块详解

Rocky006

于 2023-11-03 17:02:59 发布

阅读量527

收藏

3

点赞数

5

文章标签:

python

开发语言

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/Rocky006/article/details/134182779

版权

1. 简介

sys模块是Python标准库中的一个内置模块,提供了与Python解释器和运行环境相关的功能。它包含了一些与系统操作和交互相关的函数和变量,可以用于获取命令行参数、控制程序的执行、管理模块和包、处理异常等。

2. 常用函数和变量

2.1 命令行参数

sys模块提供了一些函数和变量用于获取和处理命令行参数。

sys.argv:是一个包含命令行参数的列表,其中第一个元素是脚本的名称。可以使用sys.argv[1:]来获取除脚本名称外的所有参数。

sys.argv[0]:是脚本的名称。 sys.argv[1:]:是除脚本名称外的所有参数。

示例:

import sys

# 获取脚本的名称

script_name = sys.argv[0]

print("脚本名称:", script_name)

# 获取除脚本名称外的所有参数

args = sys.argv[1:]

print("参数列表:", args)

2.2 系统相关

sys模块还提供了一些函数和变量用于与系统相关的操作。 sys.platform:是一个字符串,表示当前运行的操作系统平台。 sys.version:是一个字符串,表示当前Python解释器的版本。 sys.exit([arg]):用于退出程序,可选地指定一个整数参数作为退出状态码。

示例:​​​​​​​

import sys

# 获取当前操作系统平台

platform = sys.platform

print("操作系统平台:", platform)

# 获取当前Python解释器的版本

version = sys.version

print("Python版本:", version)

# 退出程序

sys.exit(0)

2.3 模块和包

sys模块还提供了一些函数和变量用于管理模块和包。

sys.modules:是一个字典,包含了当前已导入的所有模块。 sys.path:是一个列表,包含了Python解释器在搜索模块时要查找的路径。 sys.meta_path:是一个列表,包含了当前已注册的所有导入钩子。

示例:​​​​​​​

import sys

# 获取已导入的所有模块

modules = sys.modules

print("已导入的模块:", modules)

# 获取模块搜索路径

path = sys.path

print("模块搜索路径:", path)

# 获取已注册的导入钩子

meta_path = sys.meta_path

print("已注册的导入钩子:", meta_path)

2.4 异常处理

sys模块还提供了一些函数和变量用于处理异常。

sys.exc_info():返回当前异常的相关信息,包括异常类型、异常值和异常追踪信息。 sys.exc_clear():清除当前异常。 sys.exc_type:是一个变量,保存了当前异常的类型。 sys.exc_value:是一个变量,保存了当前异常的值。 sys.exc_traceback:是一个变量,保存了当前异常的追踪信息。 示例:​​​​​​​

import sys

try:

# 产生一个异常

raise ValueError("发生了一个错误")

except:

# 获取当前异常的相关信息

exc_type, exc_value, exc_traceback = sys.exc_info()

print("异常类型:", exc_type)

print("异常值:", exc_value)

print("异常追踪信息:", exc_traceback)

# 清除当前异常

sys.exc_clear()

3. 总结

sys模块是Python标准库中的一个内置模块,提供了与Python解释器和运行环境相关的功能。它包含了一些与系统操作和交互相关的函数和变量,可以用于获取命令行参数、控制程序的执行、管理模块和包、处理异常等。通过使用sys模块,我们可以更好地了解和控制程序的运行环境,提高程序的灵活性和可靠性。

优惠劵

Rocky006

关注

关注

5

点赞

3

收藏

觉得还不错?

一键收藏

打赏

知道了

0

评论

Python中的sys模块详解

sys模块是Python标准库中的一个内置模块,提供了与Python解释器和运行环境相关的功能。它包含了一些与系统操作和交互相关的函数和变量,可以用于获取命令行参数、控制程序的执行、管理模块和包、处理异常等。

复制链接

扫一扫

Python中sys模块功能与用法实例详解

12-20

本文实例讲述了Python中sys模块功能与用法。分享给大家供大家参考,具体如下:

sys-系统特定的参数和功能

该模块提供对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数。它始终可用。

sys.argv

传递给Python脚本的命令行参数列表。argv[0]是脚本名称(依赖于操作系统,无论这是否是完整路径名)。如果使用-c解释器的命令行选项执行命令,argv[0]则将其设置为字符串’-c’。如果没有脚本名称传递给Python解释器,argv[0]则为空字符串。

要循环标准输入或命令行上给出的文件列表,请参阅fileinput模块。

sys.byteorder

本机字节顺序的

python之sys模块

热门推荐

zyc_love_study的博客

01-05

6万+

python版本: Python 2.7.6

1: sys是python自带模块.

利用 import 语句输入sys 模块。

当执行import sys后, python在 sys.path 变量中所列目录中寻找 sys 模块文件。然后运行这个模块的主块中的语句进行初始化,然后就可以使用模块了 。

2: sys模块常见函数

可以通过dir()方法查看模块中可用的方法. 结果如下, 很

参与评论

您还未登录,请先

登录

后发表或查看评论

Python命令行解析模块详解

01-20

本文研究的主要是Python命令行解析模块的相关内容,具体如下。

Python命令行常见的解析器有两种,一是getopt模块,二是argparse模块。下面就解读下这两种解析器。

getopt模块

这个模块可以帮助脚本解析命令行参数,一般是sys.argv[1:]。它遵循着Unix的getopt()函数相同的约定(用-/–指定命令参数)。这个模块提供两个函数(getopt.getopt()/getopt.gnu_getopt())和一个参数异常(getopt.GetoptError)。

这里重点介绍getopt.getopt()这个函数。

函数原型:getopt.getopt(args,

python标准库(一) :sys模块常用方法详解

qq_19788525的博客

10-13

2052

一、sys的用处和场景

sys是system的缩写,用来获取操作系统和编译器的一些配置,设置及操作

以下几个方法在工作面试都几乎是必问的,很多人知其然不知所以然

现在深入浅出的实践并学习下这个工作中必用模块的一些方法

1、sys.argv():

sys.argv就是一个从程序外部获取参数的桥梁,这个“外部”很关键, 因为我们从外部取得的参数可以是多个

sys.argv其实可以看作是一个...

【python】python的标准库——sys模块介绍

sinat_41752325的博客

09-22

870

python中的sys模块说明

Python标准库之Sys模块使用详解

12-24

sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分.

处理命令行参数

在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称.

使用sys模块获得脚本的参数

复制代码 代码如下:

print “script name is”, sys.argv[0]        # 使用sys.argv[0]采集脚本名称

if len(sys.argv) > 1:

    print “there are”, len(sys.argv)-1, “arguments:”  # 使用len(sys.argv)-1采集参数个数-1为减去[0]脚本名称

python之sys模块详解

wu_zhiyuan的博客

05-12

3万+

前言

sys模块是与python解释器交互的一个接口。sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分。

处理命令行参数

在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称。

sys.argv[0] 表示程序自身

sys.argv[1] 表示程序的第一个参数

sys.argv[2] 表示程序的第二个参数

可以做个测试,如下图:

sys.exit(n) 退出程序,正常退出时exit(0)

#!/usr/bin/env python

# -

Python学习第七篇:sys标准库

Goodric的博客

08-16

6410

​Python的sys模块提供访问由解释器使用或维护的变量的接口,并提供了一些函数用来和解释器进行交互,操控Python的运行时环境。

python系统模块:sys全解

微小冷的学习笔记

12-07

6457

sys模块

命令行传参

argv和orig_argv可以起到传递命令行参数的作用。例如新建python文件testArgv.py:

import sys

print(sys.argv)

print(sys.orig_argv)

保存之后,在命令行输入

>python testArgv.py ab cde fg

['testArgv.py', 'ab', 'cde', 'fg']

['python', 'testArgv.py', 'ab', 'cde', 'fg']

>python testA

Python常用标准库-sys库一文详解

master_hunter的博客

02-28

5424

补全一下Python的基础库功能篇,之前一直写pandas和机器学习模型,偶尔换个口味写写基础的。下一作专栏估计会将文本挖掘技术和爬虫技术结合起来出一期,敬请期待。Python 标准库非常庞大,所提供的组件涉及范围十分广泛,正如以下内容目录所显示的。这个库包含了多个内置模块 (以 C 编写),Python 程序员必须依靠它们来实现系统级功能,例如文件 I/O,此外还有大量以 Python 编写的模块,提供了日常编程中许多问题的标准解决方案。

Python sys模块

qq_36594703的博客

05-18

1391

sys” 即 “system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。

Python之sys模块详解

weixin_30247307的博客

03-15

272

sys模块的介绍

sys模块是python自带的内建模块,可以直接导入使用的模块。他的作用是查询和设置系统信息。

由于sys模块的功能很多,我们只介绍一些常用的功能。

sys模块常见函数列表

. sys.argv:接收向程序传递的参数。返回值是一个列表,元素是传递的参数. sys.exit([0]):退出程序,arg=0为正常退出. sys.getdefaulte...

cpython 标准库_Python常用标准库之sys

weixin_39836536的博客

11-29

74

Python常用标准库之syssys模块主要是针对与Python解释器相关的变量和方法,不是主机操作系统。导入方式:import syssys.argv #获取命令行参数列表,第一个元素是程序本身sys.exit(n) #退出Python程序,exit(0)表示正常退出。当参数非0时,会引发一个SystemExit异常,可以在程序中捕获该异常sys.version #获取Python解释程器...

python sys模块详解

爱死亡机器人

06-11

2442

sys介绍

“sys”即“system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。

常用方法

sys.argv

“argv”即“argument value”的简写,是一个列表对象,其中存储的是在命令行调用 Python 脚本时提供的“命令行参数”。

这个列表中的第一个参数是被调用的脚本名称,也就是说,调用 Python 解释器的“命令”(python)本身并没有被加入这个列表当中。

import

python中sys模块

菜鸟更要努力呀

06-25

5328

1 sys.argv:

实现从程序外部向程序传递参数。其中sys.argv[0]通常就是指该python程序,sys.argv[1]代表为python提供的第一个参数,sys.argv[2]代表为python提供的第二个参数。

2 sys.exit([arg]):

退出程序,正常退出时exit(0),一般情况下执行到程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit...

Python模块之sys

lienze.tech

10-12

182

前言

这几年一直在it行业里摸爬滚打,一路走来,不少总结了一些python行业里的高频面试,看到大部分初入行的新鲜血液,还在为各样的面试题答案或收录有各种困难问题

于是乎,我自己开发了一款面试宝典,希望能帮到大家,也希望有更多的Python新人真正加入从事到这个行业里,让python火不只是停留在广告上。

微信小程序搜索:Python面试宝典

或可关注原创个人博客:https://lienze.tech

也可关注微信公众号,不定时发送各类有趣猎奇的技术文章:Python编程学习

sys模块

sys模块提供访

python中sys.path详解

最新发布

06-06

sys.path是Python中一个很重要的变量,他存放着模块搜索路径的列表,在Python解释器寻找模块时将会根据sys.path中存放的路径进行搜索。

在一般情况下,sys.path中的路径由以下几部分组成:

1. 系统默认路径:这些路径包括Python安装目录内的标准库路径等。

2. 环境变量PYTHONPATH中指定的路径:如果我们设置了PYTHONPATH环境变量,指向了一个文件夹,那么该文件夹路径也会被加入到sys.path中。

3. 当前目录:Python模块搜索路径还包括当前运行脚本所在的目录。

4. site-packages目录:site-packages目录存放了所有的第三方库,如果我们需要安装一些别的插件,那么这些插件也会被安装在这个目录下。

对sys.path进行修改的方法:

1. sys.path.append(path):在sys.path列表的末尾添加一个新的路径,该路径将优先于默认路径被搜索。

2. sys.path.insert(index, path):在sys.path列表的指定索引处插入一个新的路径,该路径将优先于默认路径被搜索。

3. sys.path.remove(path):从sys.path列表中删除指定的路径。

4. sys.path.clear():清空sys.path列表中所有的路径。

总之,sys.path是Python中非常重要的变量,它决定了Python寻找模块的路径,我们可以通过它来添加或修改模块搜索路径,从而较为灵活地管理Python包和模块。

“相关推荐”对你有帮助么?

非常没帮助

没帮助

一般

有帮助

非常有帮助

提交

Rocky006

CSDN认证博客专家

CSDN认证企业博客

码龄1年

暂无认证

520

原创

3965

周排名

2120

总排名

87万+

访问

等级

9812

积分

4687

粉丝

4398

获赞

217

评论

5797

收藏

私信

关注

热门文章

一觉醒后ChatGPT 被淘汰了

136475

程序员的下一个风口

48131

一文看懂python如何执行cmd命令

24494

Linux操作系统学习——启动

22742

微信为什么使用 SQLite 保存聊天记录?

22430

最新评论

Python 语法高亮显示和格式化库之pygments使用详解

江城开朗的豌豆:

总结的很详细,文章有深度,内容丰富,干货满满,期待博主持续更新,三连支持!!!

Python 额外工具库之boltons使用详解

Rocky006:

感谢大佬的肺腑之言,让我们共同进步学习

Python 额外工具库之boltons使用详解

江城开朗的豌豆:

大佬的文章让我对这领域的技术问题有了更深入的了解,尤其是大佬提到的那些“坑点”,我相信能够在实际应用中避免或解决很多问题。谢谢大佬的分享,期待大佬的更多精彩文章,让我们共同学习、进步

Python处理表格数据库之Agate使用详解

Rocky006:

感谢大佬的支持后续会更加努力写出优质的文章

Python处理表格数据库之Agate使用详解

江城开朗的豌豆:

博文使用通俗易懂的语言,避免了过于专业术语的使用,并提供了清晰的解释和说明,使读者能够轻松理解和跟随。支持

您愿意向朋友推荐“博客详情页”吗?

强烈不推荐

不推荐

一般般

推荐

强烈推荐

提交

最新文章

Python 语法高亮显示和格式化库之pygments使用详解

Python 异步文件操作库之aiofiles使用详解

Python 机器学习模型库之lazypredict使用详解

2024

03月

12篇

02月

37篇

01月

58篇

2023年413篇

目录

目录

最新文章

Python 语法高亮显示和格式化库之pygments使用详解

Python 异步文件操作库之aiofiles使用详解

Python 机器学习模型库之lazypredict使用详解

2024

03月

12篇

02月

37篇

01月

58篇

2023年413篇

目录

评论

被折叠的  条评论

为什么被折叠?

到【灌水乐园】发言

查看更多评论

添加红包

祝福语

请填写红包祝福语或标题

红包数量

红包个数最小为10个

红包总金额

红包金额最低5元

余额支付

当前余额3.43元

前往充值 >

需支付:10.00元

取消

确定

下一步

知道了

成就一亿技术人!

领取后你会自动成为博主和红包主的粉丝

规则

hope_wisdom 发出的红包

打赏作者

Rocky006

你的鼓励将是我创作的最大动力

¥1

¥2

¥4

¥6

¥10

¥20

扫码支付:¥1

获取中

扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元

使用余额支付

点击重新获取

扫码支付

钱包余额

0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值

【Python】sys库介绍-CSDN博客

>

【Python】sys库介绍-CSDN博客

【Python】sys库介绍

姚路遥遥

已于 2023-03-07 23:52:15 修改

阅读量1.6w

收藏

111

点赞数

16

分类专栏:

Python

文章标签:

python

linux

window

深度学习

神经网络

于 2021-02-03 00:09:24 首次发布

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/Roaddd/article/details/113576837

版权

Python

专栏收录该内容

12 篇文章

8 订阅

订阅专栏

sys库

       sys模块是最常用的和python解释器交互的模块,sys模块可供访问由解释器(interpreter)使用或维护的变量和与解释器进行交互的函数。sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分。

sys.argv命令行参数List,第一个元素是程序本身路径sys.path返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.modules.keys()返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.modules返回系统导入的模块字段,key是模块名,value是模块sys.modules.keys()返回所有已经导入的模块列表sys.exc_info()获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息sys.exit(n)退出程序,正常退出时exit(0)sys.hexversion获取Python解释程序的版本值,16进制格式如:0x020403F0sys.version获取Python解释程序的版本信息sys.platform返回操作系统平台名称sys.stdout标准输出sys.stdout.write(‘aaa‘)标准输出内容sys.stdout.writelines()无换行输出sys.stdin标准输入sys.stdin.read()输入一行sys.stderr错误输出sys.exc_clear()用来清除当前线程所出现的当前的或最近的错误信息sys.exec_prefix返回平台独立的python文件安装的位置sys.byteorder本地字节规则的指示器,big-endian平台的值是‘big‘,little-endian平台的值是‘little‘sys.copyright记录python版权相关的东西sys.api_version解释器的C的API版本sys.version_info‘final‘表示最终,也有‘candidate‘表示候选,表示版本级别,是否有后继的发行sys.getdefaultencoding()返回当前你所用的默认的字符编码格式sys.getfilesystemencoding()返回将Unicode文件名转换成系统文件名的编码的名字sys.builtin_module_namesPython解释器导入的内建模块列表sys.executablePython解释程序路径sys.getwindowsversion()获取Windows的版本sys.stdin.readline()从标准输入读一行,sys.stdout.write(“a”) 屏幕输出asys.setdefaultencoding(name)用来设置当前默认的字符编码(详细使用参考文档)sys.displayhook(value)如果value非空,这个函数会把他输出到sys.stdout(详细使用参考文档)

关注博主即可阅读全文

优惠劵

姚路遥遥

关注

关注

16

点赞

111

收藏

觉得还不错?

一键收藏

知道了

2

评论

【Python】sys库介绍

sys库       sys模块是最常用的和python解释器交互的模块,sys模块可供访问由解释器(interpreter)使用或维护的变量和与解释器进行交互的函数。sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分。sys.argv命令行参数List,第一个元素是程序本身路径sys.path返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.modules

复制链接

扫一扫

专栏目录

Python标准库之Sys模块使用详解

09-22

主要介绍了Python标准库之Sys模块使用详解,本文讲解了使用sys模块获得脚本的参数、处理模块、使用sys模块操作模块搜索路径、使用sys模块查找内建模块、使用sys模块查找已导入的模块等使用案例,需要的朋友可以参考下

python常用库

10-17

通过分析github上5000多个开源python项目,找出最常用的库,例如os、os.path、glob、sys、re、logging、subprocess、time、datetime、urllib、random、telnetlib、paramiko

2 条评论

您还未登录,请先

登录

后发表或查看评论

【Python】sys库的介绍及用法

最新发布

qq_53871375的博客

01-27

827

Python的sys库是一种内建模块,可对Python的运行环境进行访问和操作。如果你运行 python myscript.py arg1 arg2,将打印出 ['myscript.py', 'arg1', 'arg2']。sys.modules是一个全局字典,它保存了所有已经导入的Python模块。字典的键是模块的名称,值就是模块对象本身。sys.modules不仅包括由你在代码中导入的模块,还包括Python在启动时自动导入的一些基础模块。以上代码会打印出 Python 搜索模块的路径集。

python的sys无法安装_Python sys 模块详解

weixin_39851408的博客

01-24

1250

Python sys 模块详解1. 简介“sys”即“system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。2. 常用功能2.1 sys.argv“argv”即“argument value”的简写,是一个列表对象,其中存储的是在命令行调用 Python 脚本时提供的“命令行参数”。这个...

python中sys模块是做什么用的

12-17

python中的sys是提供了一系列有关python运行环境的变量和函数的模块,如sys.argv函数实现从程序外部向程序传递参数;sys.platform函数用于获取当前系统平台。

sys模块提供了一系列有关Python运行环境的变量和函数。

sys模块的常见函数列表

sys.argv: 实现从程序外部向程序传递参数。

sys.exit([arg]): 程序中间的退出,arg=0为正常退出。

sys.getdefaultencoding(): 获取系统当前编码,一般默认为ascii。

sys.setdefaultencoding(): 设置系统默认编码,执行dir(sys)时

配置表 | 全方位认识 sys 系统库

老叶茶馆

11-30

904

在上一篇《初相识 | 全方位认识 sys 系统库》中,我们针对sys 系统库做了一个不痛不痒的开端,是不是觉得太简单了?别急,本期我们将为大家带来系列第二篇《配置表|全方位认识 sys ...

sys模块常用方法

plan_jok的博客

10-21

1156

sys模块常用方法

方法

说明

sys.argv

命令行参数List,第一个元素是程序本身路径

sys.modules.keys()

返回所有已经导入的模块列表

sys.exc_info()

获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息

sys.exit(n)

退出程序,正常退出时exit(0)

sys.hexversion

获取Python解释程序的版本值,16进制格式如:0x020403F0

sys.

Python常用标准库-sys库一文详解

master_hunter的博客

02-28

5424

补全一下Python的基础库功能篇,之前一直写pandas和机器学习模型,偶尔换个口味写写基础的。下一作专栏估计会将文本挖掘技术和爬虫技术结合起来出一期,敬请期待。Python 标准库非常庞大,所提供的组件涉及范围十分广泛,正如以下内容目录所显示的。这个库包含了多个内置模块 (以 C 编写),Python 程序员必须依靠它们来实现系统级功能,例如文件 I/O,此外还有大量以 Python 编写的模块,提供了日常编程中许多问题的标准解决方案。

Python学习第七篇:sys标准库

Goodric的博客

08-16

6410

​Python的sys模块提供访问由解释器使用或维护的变量的接口,并提供了一些函数用来和解释器进行交互,操控Python的运行时环境。

python中sys库用法详解

IT之一小佬的博客

03-13

3076

Python中sys模块:该模块提供对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数# sys.argv #命令行参数List,第一个元素是程序本身路径# sys.modules.keys() #返回所有已经导入的模块列表# sys.exc_info() #获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息# sys.exit(n) #程序,正常退出时exit(0)

python sys库

qq_38327117的博客

06-22

6448

python sys库

Python库 | systest-2.1.0.tar.gz

04-15

资源分类:Python库 所属语言:Python 资源全名:systest-2.1.0.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

Python库 | os_sys-1.9.1-py3-none-any.whl

04-30

资源分类:Python库 所属语言:Python 资源全名:os_sys-1.9.1-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

Python中sys模块

热门推荐

宇宙无敌大帅锅

08-16

20万+

sys-系统特定的参数和功能

该模块提供对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数。它始终可用。

sys.argv

传递给Python脚本的命令行参数列表。argv[0]是脚本名称(依赖于操作系统,无论这是否是完整路径名)。如果使用-c解释器的命令行选项执行命令,argv[0]则将其设置为字符串’-c’。如果没有脚本名称传递给Python解释器,argv[0]则为空字符串...

Python sys模块

qq_36594703的博客

05-18

1391

sys” 即 “system”,“系统”之意。该模块提供了一些接口,用于访问 Python 解释器自身使用和维护的变量,同时模块中还提供了一部分函数,可以与解释器进行比较深度的交互。

python之sys库

weixin_44534915的博客

02-25

514

python之sys库

漫谈MySQL六-系统数据库sys库详解

b379685397的博客

02-11

4455

目录

1.sys介绍

2.sys 系统库使用

2.1.查看慢 SQL 语句慢在哪里

2.2.查询表的增、删、改、查数据量和 I/O 耗时统计

3.sys小结

大家好,我是王老狮,平时我们在使用mysql中经常遇到慢sql以及想要了解sql执行的性能如何。那我们应该从哪里获取这些信息呢?今天我们就来聊一聊SYS库,来找一找答案。

1.sys介绍

sys 系统库通常都是提供给专业的 DBA 人员排查一些特定问题使用的,其下所涉及的各项查询或多或少都会对性能有一定的影响。所以这个库的配...

Python 标准库: sys 模块

onebutterfly

06-19

371

注意: sys.builtin_module_names该属性是一个字符串元组,但是其中的元素为当前所使用的的 Python 解释器内置的模块名称。该属性是字符串组成的列表,其列表中的每个元素表示的是 Python 搜索模块的路径(在程序启动期间被初始化)——前者的关键字(keys)列出的是导入的模块名,而后者则是解释器内置的模块)的值是最初调用 Python 解释器的脚本所在的绝对路径;该属性是一个字典,包含的是各种已加载的模块的模块名到模块具体位置的映射。6、sys.stdin和sys.stdout。

“相关推荐”对你有帮助么?

非常没帮助

没帮助

一般

有帮助

非常有帮助

提交

姚路遥遥

CSDN认证博客专家

CSDN认证企业博客

码龄5年

暂无认证

163

原创

1319

周排名

3万+

总排名

65万+

访问

等级

3718

积分

2万+

粉丝

624

获赞

167

评论

3332

收藏

私信

关注

热门文章

【注意力机制】CBAM详解(文末附代码)

118530

正态分布&标准正态分布

22953

【Python】line.strip().split(‘,‘)含义

21783

【轻量级网络】MobileNet-v2详解

20582

win10安装CUDA和cuDNN详解

19056

分类专栏

机器学习

21篇

人脸识别

19篇

Python

12篇

激活函数

7篇

数据结构与算法

2篇

注意力机制

2篇

图像分类

4篇

知识蒸馏

1篇

人脸检测

2篇

bug记录

6篇

正则化

3篇

Pytorch

4篇

AI面试题

14篇

深度学习环境

2篇

语义分割

1篇

目标检测

13篇

最新评论

【正则化】DropBlock详解

喝无糖雪碧:

代码有些问题吧,生成mask的时候,随机drop的点的范围没有限制到(feat_size-block_size//2)*(feat_size-block_size//2)里面,导致后面最大池化生成的block在边缘的地方不是正方形。

【注意力机制】CBAM详解(文末附代码)

姚路遥遥:

直接print模型就可以看网络结构,你这个问题可能是forward的时候没有执行,你确认下

【人脸识别/轻量级模型】MobileFaceNet:适用于人脸识别的轻量级网络模型(文末附pytorch代码)

Kr.stylish:

请问有在Ms-Celeb-1M的上的预训练模型吗?

【注意力机制】CBAM详解(文末附代码)

GUET-20082304083:

你好up,请问CBAM可以用torchviz、hiddenlayer这样的网络可视化工具显示出来吗?

我把它加在网络里,输出的结构与原网络没有区别。

【opencv】图像处理之伽马变换

gyf的blog:

你这个讨论有点傻啊,伽马是指数变换,像素值大的增加就更多,跟整体相加一个数能一个样吗

您愿意向朋友推荐“博客详情页”吗?

强烈不推荐

不推荐

一般般

推荐

强烈推荐

提交

最新文章

【自监督学习】对比学习(Contrastive Learning)介绍

【机器学习】什么是监督学习、半监督学习、无监督学习、自监督学习以及弱监督学习

【数据结构与算法】数据结构有哪些?算法有哪些?

2023年15篇

2022年11篇

2021年123篇

2020年16篇

目录

目录

分类专栏

机器学习

21篇

人脸识别

19篇

Python

12篇

激活函数

7篇

数据结构与算法

2篇

注意力机制

2篇

图像分类

4篇

知识蒸馏

1篇

人脸检测

2篇

bug记录

6篇

正则化

3篇

Pytorch

4篇

AI面试题

14篇

深度学习环境

2篇

语义分割

1篇

目标检测

13篇

目录

评论 2

被折叠的  条评论

为什么被折叠?

到【灌水乐园】发言

查看更多评论

添加红包

祝福语

请填写红包祝福语或标题

红包数量

红包个数最小为10个

红包总金额

红包金额最低5元

余额支付

当前余额3.43元

前往充值 >

需支付:10.00元

取消

确定

下一步

知道了

成就一亿技术人!

领取后你会自动成为博主和红包主的粉丝

规则

hope_wisdom 发出的红包

实付元

使用余额支付

点击重新获取

扫码支付

钱包余额

0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值

操作系统实用工具 — Python 3.12.2 文档

操作系统实用工具 — Python 3.12.2 文档

Theme

Auto

Light

Dark

目录

操作系统实用工具

系统功能

过程控制

上一主题

工具

下一主题

导入模块

当前页面

报告 Bug

显示源码

导航

索引

模块 |

下一页 |

上一页 |

Python »

3.12.2 Documentation »

Python/C API 参考手册 »

工具 »

操作系统实用工具

|

Theme

Auto

Light

Dark

|

操作系统实用工具¶

PyObject *PyOS_FSPath(PyObject *path)¶

返回值:新的引用。 属于 稳定 ABI 自 3.6 版开始.返回 path 在文件系统中的表示形式。 如果该对象是一个 str 或 bytes 对象,则返回一个新的 strong reference。 如果对象实现了 os.PathLike 接口,则只要它是一个 str 或 bytes 对象就将返回 __fspath__()。 在其他情况下将引发 TypeError 并返回 NULL。

在 3.6 版本加入.

int Py_FdIsInteractive(FILE *fp, const char *filename)¶

如果名称为 filename 的标准Return true (nonzero) if the standard I/O 文件 fp 被确认为可交互的则返回真(非零)值。 所有 isatty(fileno(fp)) 为真值的文件都属于这种情况。 如果 PyConfig.interactive 为非零值,此函数在 filename 指针为 NULL 或者其名称等于字符串 '' 或 '???' 之一时也将返回真值。

此函数不可在 Python 被初始化之前调用。

void PyOS_BeforeFork()¶

属于 稳定 ABI on platforms with fork() 自 3.7 版开始.在进程分叉之前准备某些内部状态的函数。 此函数应当在调用 fork() 或者任何类似的克隆当前进程的函数之前被调用。 只适用于定义了 fork() 的系统。

警告

C fork() 调用应当只在 "main" 线程 (位于 "main" 解释器) 中进行。 对于 PyOS_BeforeFork() 来说也是如此。

在 3.7 版本加入.

void PyOS_AfterFork_Parent()¶

属于 稳定 ABI on platforms with fork() 自 3.7 版开始.在进程分叉之后更新某些内部状态的函数。 此函数应当在调用 fork() 或任何类似的克隆当前进程的函数之后被调用,无论进程克隆是否成功。 只适用于定义了 fork() 的系统。

警告

C fork() 调用应当只在 "main" 线程 (位于 "main" 解释器) 中进行。 对于 PyOS_AfterFork_Parent() 来说也是如此。

在 3.7 版本加入.

void PyOS_AfterFork_Child()¶

属于 稳定 ABI on platforms with fork() 自 3.7 版开始.在进程分叉之后更新内部解释器状态的函数。 此函数必须在调用 fork() 或任何类似的克隆当前进程的函数之后在子进程中被调用,如果该进程有机会回调到 Python 解释器的话。 只适用于定义了 fork() 的系统。

警告

C fork() 调用应当只在 "main" 线程 (位于 "main" 解释器) 中进行。 对于 PyOS_AfterFork_Child() 来说也是如此。

在 3.7 版本加入.

参见

os.register_at_fork() 允许注册可被 PyOS_BeforeFork(), PyOS_AfterFork_Parent() 和 PyOS_AfterFork_Child() 调用的自定义 Python 函数。

void PyOS_AfterFork()¶

属于 稳定 ABI on platforms with fork().在进程分叉之后更新某些内部状态的函数;如果要继续使用 Python 解释器则此函数应当在新进程中被调用。 如果已将一个新的可执行文件载入到新进程中,则不需要调用此函数。

自 3.7 版本弃用: 此函数已被 PyOS_AfterFork_Child() 取代。

int PyOS_CheckStack()¶

属于 稳定 ABI on platforms with USE_STACKCHECK 自 3.7 版开始.当解释器耗尽栈空间时返回真值。 这是一个可靠的检测,但仅在定义了 USE_STACKCHECK 时可用(目前是在使用 Microsoft Visual C++ 编译器的特定 Windows 版本上)。 USE_STACKCHECK 将被自动定义;你绝不应该在你自己的代码中改变此定义。

typedef void (*PyOS_sighandler_t)(int)¶

属于 稳定 ABI.

PyOS_sighandler_t PyOS_getsig(int i)¶

属于 稳定 ABI.返回信号 i 当前的信号处理句柄。 这是一个对 sigaction() 或 signal() 的简单包装器。 请不要直接调用这两个函数!

PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)¶

属于 稳定 ABI.将信号 i 的信号处理句柄设为 h;返回原来的信号处理句柄。 这是一个对 sigaction() 或 signal() 的简单包装器。 请不要直接调用这两个函数!

wchar_t *Py_DecodeLocale(const char *arg, size_t *size)¶

属于 稳定 ABI 自 3.7 版开始.

警告

此函数不应当被直接调用:请使用 PyConfig API 以及可确保 对 Python 进行预初始化 的 PyConfig_SetBytesString() 函数。

此函数不可在This function must not be called before 对 Python 进行预初始化 之前被调用以便正确地配置 LC_CTYPE 语言区域:请参阅 Py_PreInitialize() 函数。

使用 filesystem encoding and error handler 来解码一个字节串。 如果错误处理句柄为 surrogateescape 错误处理句柄,则不可解码的字节将被解码为 U+DC80..U+DCFF 范围内的字符;而如果一个字节序列可被解码为代理字符,则其中的字节会使用 surrogateescape 错误处理句柄来转义而不是解码它们。

返回一个指向新分配的由宽字符组成的字符串的指针,使用 PyMem_RawFree() 来释放内存。 如果 size 不为 NULL,则将排除了 null 字符的宽字符数量写入到 *size

在解码错误或内存分配错误时返回 NULL。 如果 size 不为 NULL,则 *size 将在内存错误时设为 (size_t)-1 或在解码错误时设为 (size_t)-2。

filesystem encoding and error handler 是由 PyConfig_Read() 来选择的: 参见 PyConfig 的 filesystem_encoding 和 filesystem_errors 等成员。

解码错误绝对不应当发生,除非 C 库有程序缺陷。

请使用 Py_EncodeLocale() 函数来将字符串编码回字节串。

参见

PyUnicode_DecodeFSDefaultAndSize() 和 PyUnicode_DecodeLocaleAndSize() 函数。

在 3.5 版本加入.

在 3.7 版本发生变更: 现在此函数在 Python UTF-8 模式 下将使用 UTF-8 编码格式。

在 3.8 版本发生变更: 现在如果在 Windows 上 PyPreConfig.legacy_windows_fs_encoding 为零则此函数将使用 UTF-8 编码格式;

char *Py_EncodeLocale(const wchar_t *text, size_t *error_pos)¶

属于 稳定 ABI 自 3.7 版开始.将一个由宽字符组成的字符串编码为 filesystem encoding and error handler。 如果错误处理句柄为 surrogateescape 错误处理句柄,则在 U+DC80..U+DCFF 范围内的代理字符会被转换为字节值 0x80..0xFF。

返回一个指向新分配的字节串的指针,使用 PyMem_Free() 来释放内存。 当发生编码错误或内存分配错误时返回 NULL。

如果 error_pos 不为 NULL,则成功时会将 *error_pos 设为 (size_t)-1,或是在发生编码错误时设为无效字符的索引号。

filesystem encoding and error handler 是由 PyConfig_Read() 来选择的: 参见 PyConfig 的 filesystem_encoding 和 filesystem_errors 等成员。

请使用 Py_DecodeLocale() 函数来将字节串解码回由宽字符组成的字符串。

警告

此函数不可在This function must not be called before 对 Python 进行预初始化 之前被调用以便正确地配置 LC_CTYPE 语言区域:请参阅 Py_PreInitialize() 函数。

参见

PyUnicode_EncodeFSDefault() 和 PyUnicode_EncodeLocale() 函数。

在 3.5 版本加入.

在 3.7 版本发生变更: 现在此函数在 Python UTF-8 模式 下将使用 UTF-8 编码格式。

在 3.8 版本发生变更: 现在如果在 Windows 上 PyPreConfig.legacy_windows_fs_encoding 为零则此函数将使用 UTF-8 编码格式。

系统功能¶

这些是使来自 sys 模块的功能可以让 C 代码访问的工具函数。 它们都可用于当前解释器线程的 sys 模块的字典,该字典包含在内部线程状态结构体中。

PyObject *PySys_GetObject(const char *name)¶

返回值:借入的引用。 属于 稳定 ABI.返回来自 sys 模块的对象 name 或者如果它不存在则返回 NULL,并且不会设置异常。

int PySys_SetObject(const char *name, PyObject *v)¶

属于 稳定 ABI.将 sys 模块中的 name 设为 v 除非 v 为 NULL,在此情况下 name 将从 sys 模块中被删除。 成功时返回 0,发生错误时返回 -1。

void PySys_ResetWarnOptions()¶

属于 稳定 ABI.将 sys.warnoptions 重置为空列表。 此函数可在 Py_Initialize() 之前被调用。

void PySys_AddWarnOption(const wchar_t *s)¶

属于 稳定 ABI.此 API 被保留用于向下兼容:应当改为采用设置 PyConfig.warnoptions,参见 Python 初始化配置。

将 s 添加到 sys.warnoptions。 此函数必须在 Py_Initialize() 之前被调用以便影响警告过滤器列表。

自 3.11 版本弃用.

void PySys_AddWarnOptionUnicode(PyObject *unicode)¶

属于 稳定 ABI.此 API 被保留用于向下兼容:应当改为采用设置 PyConfig.warnoptions,参见 Python 初始化配置。

将 unicode 添加到 sys.warnoptions。

注意:目前此函数不可在 CPython 实现之外使用,因为它必须在 Py_Initialize() 中的 warnings 显式导入之前被调用,但是要等运行时已初始化到足以允许创建 Unicode 对象时才能被调用。

自 3.11 版本弃用.

void PySys_SetPath(const wchar_t *path)¶

属于 稳定 ABI.此 API 被保留用于向下兼容:应当改为采用设置 PyConfig.module_search_paths 和 PyConfig.module_search_paths_set,参见 Python 初始化配置。

将 sys.path 设为由在 path 中找到的路径组成的列表对象,该参数应为使用特定平台的搜索路径分隔符 (在 Unix 上为 :,在 Windows 上为 ;) 分隔的路径的列表。

自 3.11 版本弃用.

void PySys_WriteStdout(const char *format, ...)¶

属于 稳定 ABI.将以 format 描述的输出字符串写入到 sys.stdout。 不会引发任何异常,即使发生了截断(见下文)。

format 应当将已格式化的输出字符串的总大小限制在 1000 字节以下 -- 超过 1000 字节后,输出字符串会被截断。 特别地,这意味着不应出现不受限制的 "%s" 格式;它们应当使用 "%.s" 来限制,其中 是一个经计算使得 与其他已格式化文本的最大尺寸之和不会超过 1000 字节的十进制数字。 还要注意 "%f",它可能为非常大的数字打印出数以百计的数位。

如果发生了错误,sys.stdout 会被清空,已格式化的消息将被写入到真正的 (C 层级) stdout。

void PySys_WriteStderr(const char *format, ...)¶

属于 稳定 ABI.类似 PySys_WriteStdout(),但改为写入到 sys.stderr 或 stderr。

void PySys_FormatStdout(const char *format, ...)¶

属于 稳定 ABI.类似 PySys_WriteStdout() 的函数将会使用 PyUnicode_FromFormatV() 来格式化消息并且不会将消息截短至任意长度。

在 3.2 版本加入.

void PySys_FormatStderr(const char *format, ...)¶

属于 稳定 ABI.类似 PySys_FormatStdout(),但改为写入到 sys.stderr 或 stderr。

在 3.2 版本加入.

void PySys_AddXOption(const wchar_t *s)¶

属于 稳定 ABI 自 3.7 版开始.此 API 被保留用于向下兼容:应当改为采用设置 PyConfig.xoptions,参见 Python 初始化配置。

将 s 解析为一个由 -X 选项组成的集合并将它们添加到 PySys_GetXOptions() 所返回的当前选项映射。 此函数可以在 Py_Initialize() 之前被调用。

在 3.2 版本加入.

自 3.11 版本弃用.

PyObject *PySys_GetXOptions()¶

返回值:借入的引用。 属于 稳定 ABI 自 3.7 版开始.返回当前 -X 选项的字典,类似于 sys._xoptions。 发生错误时,将返回 NULL 并设置一个异常。

在 3.2 版本加入.

int PySys_Audit(const char *event, const char *format, ...)¶

引发一个审计事件并附带任何激活的钩子。 成功时返回零值或在失败时返回非零值并设置一个异常。

如果已添加了任何钩子,则将使用 format 和其他参数来构造一个用入传入的元组。 除 N 以外,在 Py_BuildValue() 中使用的格式字符均可使用。 如果构建的值不是一个元组,它将被添加到一个单元素元组中。 (格式选项 N 会消耗一个引用,但是由于没有办法知道此函数的参数是否将被消耗,因此使用它可能导致引用泄漏。)

请注意 # 格式字符应当总是被当作 Py_ssize_t 来处理,无论是否定义了 PY_SSIZE_T_CLEAN。

sys.audit() 会执行与来自 Python 代码的函数相同的操作。

在 3.8 版本加入.

在 3.8.2 版本发生变更: 要求 Py_ssize_t 用于 # 格式字符。 在此之前,会引发一个不可避免的弃用警告。

int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)¶

将可调用对象 hook 添加到激活的审计钩子列表。 在成功时返回零而在失败时返回非零值。 如果运行时已经被初始化,还会在失败时设置一个错误。 通过此 API 添加的钩子会针对在运行时创建的所有解释器被调用。

userData 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调用,该指针不应直接指向 Python 状态。

此函数可在 Py_Initialize() 之前被安全地调用。 如果在运行时初始化之后被调用,现有的审计钩子将得到通知并可能通过引发一个从 Exception 子类化的错误静默地放弃操作(其他错误将不会被静默)。

钩子函数总是会由引发异常的 Python 解释器在持有 GIL 的情况下调用。

请参阅 PEP 578 了解有关审计的详细描述。 在运行时和标准库中会引发审计事件的函数清单见 审计事件表。 更多细节见每个函数的文档。

如果解释器已被初始化,此函数将引发一个审计事件 sys.addaudithook 且不附带任何参数。 如果有任何现存的钩子引发了一个派生自 Exception 的异常,新的钩子将不会被添加且该异常会被清除。 因此,调用方不可假定他们的钩子已被添加除非他们能控制所有现存的钩子。

typedef int (*Py_AuditHookFunction)(const char *event, PyObject *args, void *userData)¶

钩子函数的类型。 event 是传给 PySys_Audit() 的 C 字符串事件参数。 args 会确保为一个 PyTupleObject。 userData 是传给 PySys_AddAuditHook() 的参数。

在 3.8 版本加入.

过程控制¶

void Py_FatalError(const char *message)¶

属于 稳定 ABI.打印一个致命错误消息并杀死进程。 不会执行任何清理。 此函数应当仅在检测到可能令继续使用 Python 解释器会有危险的情况时被发起调用;例如对象管理已被破坏的时候。 在 Unix 上,会调用标准 C 库函数 abort() 并将由它来尝试生成一个 core 文件。

The Py_FatalError() function is replaced with a macro which logs

automatically the name of the current function, unless the

Py_LIMITED_API macro is defined.

在 3.9 版本发生变更: 自动记录函数名称。

void Py_Exit(int status)¶

属于 稳定 ABI.退出当前进程。 这将调用 Py_FinalizeEx() 然后再调用标准 C 库函数 exit(status)。 如果 Py_FinalizeEx() 提示错误,退出状态将被设为 120。

在 3.6 版本发生变更: 来自最终化的错误不会再被忽略。

int Py_AtExit(void (*func)())¶

属于 稳定 ABI.注册一个由 Py_FinalizeEx() 调用的清理函数。 调用清理函数将不传入任何参数且不应返回任何值。 最多可以注册32 个清理函数。 当注册成功时,Py_AtExit() 将返回 0;失败时,它将返回 -1。 最后注册的清理函数会最先被调用。 每个清理函数将至多被调用一次。 由于 Python 的内部最终化将在清理函数之前完成,因此 Python API 不应被 func 调用。

目录

操作系统实用工具

系统功能

过程控制

上一主题

工具

下一主题

导入模块

当前页面

报告 Bug

显示源码

«

导航

索引

模块 |

下一页 |

上一页 |

Python »

3.12.2 Documentation »

Python/C API 参考手册 »

工具 »

操作系统实用工具

|

Theme

Auto

Light

Dark

|

© 版权所有 2001-2024, Python Software Foundation.

This page is licensed under the Python Software Foundation License Version 2.

Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.

See History and License for more information.

The Python Software Foundation is a non-profit corporation.

Please donate.

最后更新于 Mar 06, 2024 (12:34 UTC).

Found a bug?

由 Sphinx 7.2.6创建。

28.1. sys — 系统相关的参数和函数 — Python 2.7.18 文档

28.1. sys — 系统相关的参数和函数 — Python 2.7.18 文档

This document is for an old version of Python that is no longer supported.

You should upgrade and read the

Python 当前稳定版本的文档.

导航

索引

模块 |

下一页 |

上一页 |

Python »

Python 2.7.18 文档 »

Python 标准库 »

28. Python运行时服务 »

28.1. sys — 系统相关的参数和函数¶

该模块提供了一些变量和函数。这些变量可能被解释器使用,也可能由解释器提供。这些函数会影响解释器。本模块总是可用的。

sys.argv¶

一个列表,其中包含了被传递给 Python 脚本的命令行参数。 argv[0] 为脚本的名称(是否是完整的路径名取决于操作系统)。如果是通过 Python 解释器的命令行参数 -c 来执行的, argv[0] 会被设置成字符串 '-c' 。如果没有脚本名被传递给 Python 解释器, argv[0] 为空字符串。

为了遍历标准输入,或者通过命令行传递的文件列表,参照 fileinput 模块

sys.byteorder¶

本地字节顺序的指示符。在大端序(最高有效位优先)操作系统上值为 'big' ,在小端序(最低有效位优先)操作系统上为 'little' 。

2.0 新版功能.

sys.builtin_module_names¶

一个元素为字符串的元组。包含了所有的被编译进 Python 解释器的模块。(这个信息无法通过其他的办法获取, modules.keys() 只包括被导入过的模块。)

sys.call_tracing(func, args)¶

在启用跟踪时调用 func(*args) 来保存跟踪状态,然后恢复跟踪状态。这将从检查点的调试器调用,以便递归地调试其他的一些代码。

sys.copyright¶

一个字符串,包含了 Python 解释器有关的版权信息

sys._clear_type_cache()¶

清除内部的类型缓存。类型缓存是为了加速查找方法和属性的。在调试引用泄漏的时候调用这个函数 只会 清除不必要的引用。

这个函数应该只在内部为了一些特定的目的使用。

2.6 新版功能.

sys._current_frames()¶

返回一个字典,将每个线程的标识符映射到调用函数时该线程中当前活动的最顶层堆栈帧。注意 traceback 模块中的函数可以在给定帧的情况下构建调用堆栈。

这对于调试死锁最有用:本函数不需要死锁线程的配合,并且只要这些线程的调用栈保持死锁,它们就是冻结的。在调用本代码来检查栈顶的帧的那一刻,非死锁线程返回的帧可能与该线程当前活动的帧没有任何关系。

这个函数应该只在内部为了一些特定的目的使用。

2.5 新版功能.

sys.dllhandle¶

Integer specifying the handle of the Python DLL. Availability: Windows.

sys.displayhook(value)¶

If value is not None, this function prints it to sys.stdout, and saves

it in __builtin__._.

sys.displayhook is called on the result of evaluating an expression

entered in an interactive Python session. The display of these values can be

customized by assigning another one-argument function to sys.displayhook.

sys.dont_write_bytecode¶

If this is true, Python won’t try to write .pyc or .pyo files on the

import of source modules. This value is initially set to True or

False depending on the -B command line option and the

PYTHONDONTWRITEBYTECODE environment variable, but you can set it

yourself to control bytecode file generation.

2.6 新版功能.

sys.excepthook(type, value, traceback)¶

This function prints out a given traceback and exception to sys.stderr.

When an exception is raised and uncaught, the interpreter calls

sys.excepthook with three arguments, the exception class, exception

instance, and a traceback object. In an interactive session this happens just

before control is returned to the prompt; in a Python program this happens just

before the program exits. The handling of such top-level exceptions can be

customized by assigning another three-argument function to sys.excepthook.

sys.__displayhook__¶

sys.__excepthook__¶

These objects contain the original values of displayhook and excepthook

at the start of the program. They are saved so that displayhook and

excepthook can be restored in case they happen to get replaced with broken

objects.

sys.exc_info()¶

This function returns a tuple of three values that give information about the

exception that is currently being handled. The information returned is specific

both to the current thread and to the current stack frame. If the current stack

frame is not handling an exception, the information is taken from the calling

stack frame, or its caller, and so on until a stack frame is found that is

handling an exception. Here, “handling an exception” is defined as “executing

or having executed an except clause.” For any stack frame, only information

about the most recently handled exception is accessible.

If no exception is being handled anywhere on the stack, a tuple containing three

None values is returned. Otherwise, the values returned are (type, value,

traceback). Their meaning is: type gets the exception type of the exception

being handled (a class object); value gets the exception parameter (its

associated value or the second argument to raise, which is

always a class instance if the exception type is a class object); traceback

gets a traceback object (see the Reference Manual) which encapsulates the call

stack at the point where the exception originally occurred.

If exc_clear() is called, this function will return three None values

until either another exception is raised in the current thread or the execution

stack returns to a frame where another exception is being handled.

警告

Assigning the traceback return value to a local variable in a function that is

handling an exception will cause a circular reference. This will prevent

anything referenced by a local variable in the same function or by the traceback

from being garbage collected. Since most functions don’t need access to the

traceback, the best solution is to use something like exctype, value =

sys.exc_info()[:2] to extract only the exception type and value. If you do

need the traceback, make sure to delete it after use (best done with a

try … finally statement) or to call exc_info() in

a function that does not itself handle an exception.

注解

Beginning with Python 2.2, such cycles are automatically reclaimed when garbage

collection is enabled and they become unreachable, but it remains more efficient

to avoid creating cycles.

sys.exc_clear()¶

This function clears all information relating to the current or last exception

that occurred in the current thread. After calling this function,

exc_info() will return three None values until another exception is

raised in the current thread or the execution stack returns to a frame where

another exception is being handled.

This function is only needed in only a few obscure situations. These include

logging and error handling systems that report information on the last or

current exception. This function can also be used to try to free resources and

trigger object finalization, though no guarantee is made as to what objects will

be freed, if any.

2.3 新版功能.

sys.exc_type¶

sys.exc_value¶

sys.exc_traceback¶

1.5 版后已移除: Use exc_info() instead.

Since they are global variables, they are not specific to the current thread, so

their use is not safe in a multi-threaded program. When no exception is being

handled, exc_type is set to None and the other two are undefined.

sys.exec_prefix¶

A string giving the site-specific directory prefix where the platform-dependent

Python files are installed; by default, this is also '/usr/local'. This can

be set at build time with the --exec-prefix argument to the

configure script. Specifically, all configuration files (e.g. the

pyconfig.h header file) are installed in the directory

exec_prefix/lib/pythonX.Y/config, and shared library modules are

installed in exec_prefix/lib/pythonX.Y/lib-dynload, where X.Y

is the version number of Python, for example 2.7.

sys.executable¶

A string giving the absolute path of the executable binary for the Python

interpreter, on systems where this makes sense. If Python is unable to retrieve

the real path to its executable, sys.executable will be an empty string

or None.

sys.exit([arg])¶

从Python中退出。实现方式是抛出一个 SystemExit 异常。异常抛出后 try 声明的 finally 分支语句的清除动作将被出发。此动作有可能打断更外层的退出尝试。

The optional argument arg can be an integer giving the exit status

(defaulting to zero), or another type of object. If it is an integer, zero

is considered “successful termination” and any nonzero value is considered

“abnormal termination” by shells and the like. Most systems require it to be

in the range 0–127, and produce undefined results otherwise. Some systems

have a convention for assigning specific meanings to specific exit codes, but

these are generally underdeveloped; Unix programs generally use 2 for command

line syntax errors and 1 for all other kind of errors. If another type of

object is passed, None is equivalent to passing zero, and any other

object is printed to stderr and results in an exit code of 1. In

particular, sys.exit("some error message") is a quick way to exit a

program when an error occurs.

由于 exit() 最终“只是”抛出一个异常,因此当从主线程调用时,只会从进程退出;而异常不会因此被打断。

sys.exitfunc¶

This value is not actually defined by the module, but can be set by the user (or

by a program) to specify a clean-up action at program exit. When set, it should

be a parameterless function. This function will be called when the interpreter

exits. Only one function may be installed in this way; to allow multiple

functions which will be called at termination, use the atexit module.

注解

The exit function is not called when the program is killed by a signal, when a

Python fatal internal error is detected, or when os._exit() is called.

2.4 版后已移除: Use atexit instead.

sys.flags¶

The struct sequence flags exposes the status of command line flags. The

attributes are read only.

attribute – 属性

标志

debug

-d

py3k_warning

-3

division_warning

-Q

division_new

-Qnew

inspect

-i

interactive

-i

optimize

-O 或 -OO

dont_write_bytecode

-B

no_user_site

-s

no_site

-S

ignore_environment

-E

tabcheck

-t or -tt

verbose

-v

unicode

-U

bytes_warning

-b

hash_randomization

-R

2.6 新版功能.

2.7.3 新版功能: hash_randomization 属性

sys.float_info¶

A structseq holding information about the float type. It contains low level

information about the precision and internal representation. The values

correspond to the various floating-point constants defined in the standard

header file float.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.

attribute – 属性

float.h 宏

解释

epsilon

DBL_EPSILON

difference between 1 and the least value greater

than 1 that is representable as a float

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 float

max

DBL_MAX

maximum representable finite float

max_exp

DBL_MAX_EXP

maximum integer e such that radix**(e-1) is

a representable finite float

max_10_exp

DBL_MAX_10_EXP

maximum integer e such that 10**e is in the

range of representable finite floats

min

DBL_MIN

minimum positive normalized float

min_exp

DBL_MIN_EXP

minimum integer e such that radix**(e-1) is

a normalized float

min_10_exp

DBL_MIN_10_EXP

minimum integer e such that 10**e is a

normalized float

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. See section 5.2.4.2.2

of the C99 standard for an explanation of the

possible values and their meanings.

The attribute sys.float_info.dig needs further explanation. If

s is any string representing a decimal number with at most

sys.float_info.dig significant digits, then converting s to a

float and back again will recover a string representing the same decimal

value:

>>> import sys

>>> sys.float_info.dig

15

>>> s = '3.14159265358979' # decimal string with 15 significant digits

>>> format(float(s), '.15g') # convert to float and back -> same value

'3.14159265358979'

But for strings with more than sys.float_info.dig significant digits,

this isn’t always true:

>>> s = '9876543211234567' # 16 significant digits is too many!

>>> format(float(s), '.16g') # conversion changes value

'9876543211234568'

2.6 新版功能.

sys.float_repr_style¶

A string indicating how the repr() function behaves for

floats. If the string has value 'short' then for a finite

float x, repr(x) aims to produce a short string with the

property that float(repr(x)) == x. This is the usual behaviour

in Python 2.7 and later. Otherwise, float_repr_style has value

'legacy' and repr(x) behaves in the same way as it did in

versions of Python prior to 2.7.

2.7 新版功能.

sys.getcheckinterval()¶

Return the interpreter’s “check interval”; see setcheckinterval().

2.3 新版功能.

sys.getdefaultencoding()¶

Return the name of the current default string encoding used by the Unicode

implementation.

2.0 新版功能.

sys.getdlopenflags()¶

Return the current value of the flags that are used for dlopen() calls.

The flag constants are defined in the dl and DLFCN modules.

Availability: Unix.

2.2 新版功能.

sys.getfilesystemencoding()¶

Return the name of the encoding used to convert Unicode filenames into system

file names, or None if the system default encoding is used. The result value

depends on the operating system:

On Mac OS X, the encoding is 'utf-8'.

On Unix, the encoding is the user’s preference according to the result of

nl_langinfo(CODESET), or None if the nl_langinfo(CODESET)

failed.

On Windows NT+, file names are Unicode natively, so no conversion is

performed. getfilesystemencoding() still returns 'mbcs', as

this is the encoding that applications should use when they explicitly

want to convert Unicode strings to byte strings that are equivalent when

used as file names.

On Windows 9x, the encoding is 'mbcs'.

2.3 新版功能.

sys.getrefcount(object)¶

Return the reference count of the object. The count returned is generally one

higher than you might expect, because it includes the (temporary) reference as

an argument to getrefcount().

sys.getrecursionlimit()¶

Return the current value of the recursion limit, the maximum depth of the Python

interpreter stack. This limit prevents infinite recursion from causing an

overflow of the C stack and crashing Python. It can be set by

setrecursionlimit().

sys.getsizeof(object[, default])¶

Return the size of an object in bytes. The object can be any type of

object. All built-in objects will return correct results, but this

does not have to hold true for third-party extensions as it is implementation

specific.

If given, default will be returned if the object does not provide means to

retrieve the size. Otherwise a TypeError will be raised.

getsizeof() calls the object’s __sizeof__ method and adds an

additional garbage collector overhead if the object is managed by the garbage

collector.

2.6 新版功能.

sys._getframe([depth])¶

Return a frame object from the call stack. If optional integer depth is

given, return the frame object that many calls below the top of the stack. If

that is deeper than the call stack, ValueError is raised. The default

for depth is zero, returning the frame at the top of the call stack.

CPython implementation detail: This function should be used for internal and specialized purposes only.

It is not guaranteed to exist in all implementations of Python.

sys.getprofile()¶

Get the profiler function as set by setprofile().

2.6 新版功能.

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.

2.6 新版功能.

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, and product_type.

service_pack contains a string while all other values are

integers. The components can also be accessed by name, so

sys.getwindowsversion()[0] is equivalent to

sys.getwindowsversion().major. For compatibility with prior

versions, only the first 5 elements are retrievable by indexing.

platform may be one of the following values:

常数

Platform

0 (VER_PLATFORM_WIN32s)

Win32s on Windows 3.1

1 (VER_PLATFORM_WIN32_WINDOWS)

Windows 95/98/ME

2 (VER_PLATFORM_WIN32_NT)

Windows NT/2000/XP/x64

3 (VER_PLATFORM_WIN32_CE)

Windows CE

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 on OSVERSIONINFOEX() for more information

about these fields.

Availability: Windows.

2.3 新版功能.

在 2.7 版更改: Changed to a named tuple and added service_pack_minor,

service_pack_major, suite_mask, and product_type.

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 hexversion since it only really looks meaningful when viewed

as the result of passing it to the built-in hex() function. The

version_info value may be used for a more human-friendly encoding of the

same information.

The hexversion is a 32-bit number with the following layout:

Bits (big endian order)

含义

1-8

PY_MAJOR_VERSION (the 2 in

2.1.0a3)

9-16

PY_MINOR_VERSION (the 1 in

2.1.0a3)

17-24

PY_MICRO_VERSION (the 0 in

2.1.0a3)

25-28

PY_RELEASE_LEVEL (0xA for alpha,

0xB for beta, 0xC for release

candidate and 0xF for final)

29-32

PY_RELEASE_SERIAL (the 3 in

2.1.0a3, zero for final releases)

Thus 2.1.0a3 is hexversion 0x020100a3.

1.5.2 新版功能.

sys.long_info¶

A struct sequence that holds information about Python’s

internal representation of integers. The attributes are read only.

属性

解释

bits_per_digit

number of bits held in each digit. Python

integers are stored internally in base

2**long_info.bits_per_digit

sizeof_digit

用于表示数字的C类型的字节大小

2.7 新版功能.

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; see chapter pdb — Python的调试器 for

more information.)

The meaning of the variables is the same as that of the return values from

exc_info() above. (Since there is only one interactive thread,

thread-safety is not a concern for these variables, unlike for exc_type

etc.)

sys.maxint¶

The largest positive integer supported by Python’s regular integer type. This

is at least 2**31-1. The largest negative integer is -maxint-1 — the

asymmetry results from the use of 2’s complement binary arithmetic.

sys.maxsize¶

The largest positive integer supported by the platform’s Py_ssize_t type,

and thus the maximum size lists, strings, dicts, and many other containers

can have.

sys.maxunicode¶

An integer giving the largest supported code point for a Unicode character. The

value of this depends on the configuration option that specifies whether Unicode

characters are stored as UCS-2 or UCS-4.

sys.meta_path¶

A list of finder objects that have their find_module()

methods called to see if one of the objects can find the module to be

imported. The find_module() method is called at least with the

absolute name of the module being imported. If the module to be imported is

contained in package then the parent package’s __path__ attribute

is passed in as a second argument. The method returns None if

the module cannot be found, else returns a loader.

sys.meta_path is searched before any implicit default finders or

sys.path.

See PEP 302 for the original specification.

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.

Note that removing a module from this dictionary is not the same as calling

reload() on the corresponding module object.

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 of PYTHONPATH.

A program is free to modify this list for its own purposes.

在 2.3 版更改: Unicode strings are no longer ignored.

参见

Module site This describes how to use .pth files to extend

sys.path.

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_hooks and the values are

the finders that are found. If a path is a valid file system path but no

explicit finder is found on sys.path_hooks then None is

stored to represent the implicit default finder should be used. If the path

is not an existing path then imp.NullImporter is set.

Originally specified in PEP 302.

sys.platform¶

This string contains a platform identifier that can be used to append

platform-specific components to sys.path, for instance.

For most Unix systems, this is the lowercased OS name as returned by uname

-s with the first part of the version as returned by uname -r appended,

e.g. 'sunos5', 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...

在 2.7.3 版更改: Since lots of code check for sys.platform == 'linux2', and there is

no essential change between Linux 2.x and 3.x, sys.platform is always

set to 'linux2', even on Linux 3.x. In Python 3.3 and later, the

value will always be set to 'linux', so it is recommended to always

use the startswith idiom presented above.

对于其他系统,值是:

系统

platform value

Linux (2.x and 3.x)

'linux2'

Windows

'win32'

Windows/Cygwin

'cygwin'

Mac OS X

'darwin'

OS/2

'os2'

OS/2 EMX

'os2emx'

RiscOS

'riscos'

AtheOS

'atheos'

参见

os.name has 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 --prefix

argument to the configure script. The main collection of Python

library modules is installed in the directory prefix/lib/pythonX.Y

while the platform independent header files (all except pyconfig.h) are

stored in prefix/include/pythonX.Y, where X.Y is the version

number of Python, for example 2.7.

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.

sys.py3kwarning¶

Bool containing the status of the Python 3 warning flag. It’s True

when Python is started with the -3 option. (This should be considered

read-only; setting it to a different value doesn’t have an effect on

Python 3 warnings.)

2.6 新版功能.

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.

sys.setdefaultencoding(name)¶

Set the current default string encoding used by the Unicode implementation. If

name does not match any available encoding, LookupError is raised.

This function is only intended to be used by the site module

implementation and, where needed, by sitecustomize. Once used by the

site module, it is removed from the sys module’s namespace.

2.0 新版功能.

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 as

sys.setdlopenflags(0). To share symbols across extension modules, call as

sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL). Symbolic names for the

flag modules can be either found in the dl module, or in the DLFCN

module. If DLFCN is not available, it can be generated from

/usr/include/dlfcn.h using the h2py script. Availability:

Unix.

2.2 新版功能.

sys.setprofile(profilefunc)¶

Set the system’s profile function, which allows you to implement a Python source

code profiler in Python. See chapter Python 分析器 for more information on the

Python profiler. 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). 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.

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.

这些事件具有以下含义:

'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 None

if 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 she has 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.

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 be registered using

settrace() for each thread being debugged.

Trace functions should have three arguments: frame, event, and

arg. frame is the current stack frame. event is a string: 'call',

'line', 'return' or 'exception'. 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 that scope, or None 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.

这些事件具有以下含义:

'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. See

Objects/lnotab_notes.txt for a detailed explanation of how this

works.

'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 None

if 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.

Note that as an exception is propagated down the chain of callers, an

'exception' event is generated at each level.

For more information on code and frame objects, refer to 标准类型层级结构.

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.

sys.settscdump(on_flag)¶

Activate dumping of VM measurements using the Pentium timestamp counter, if

on_flag is true. Deactivate these dumps if on_flag is off. The function is

available only if Python was compiled with --with-tsc. To understand

the output of this dump, read Python/ceval.c in the Python sources.

2.4 新版功能.

CPython implementation detail: This function is intimately bound to CPython implementation details and

thus not likely to be implemented elsewhere.

sys.stdin¶

sys.stdout¶

sys.stderr¶

File objects corresponding to the interpreter’s standard input, output and error

streams. stdin is used for all interpreter input except for scripts but

including calls to input() and raw_input(). stdout is used for

the output of print and expression statements and for the

prompts of input() and raw_input(). The interpreter’s own prompts

and (almost all of) its error messages go to stderr. stdout and

stderr needn’t be built-in file objects: any object is acceptable as long

as it has a write() method that takes a string argument. (Changing these

objects doesn’t affect the standard I/O streams of processes executed by

os.popen(), os.system() or the exec*() family of functions in

the os module.)

sys.__stdin__¶

sys.__stdout__¶

sys.__stderr__¶

These objects contain the original values of stdin, stderr and

stdout at the start of the program. 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.

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.

sys.subversion¶

A triple (repo, branch, version) representing the Subversion information of the

Python interpreter. repo is the name of the repository, 'CPython'.

branch is a string of one of the forms 'trunk', 'branches/name' or

'tags/name'. version is the output of svnversion, if the interpreter

was built from a Subversion checkout; it contains the revision number (range)

and possibly a trailing ‘M’ if there were local modifications. If the tree was

exported (or svnversion was not available), it is the revision of

Include/patchlevel.h if the branch is a tag. Otherwise, it is None.

2.5 新版功能.

注解

Python is now developed using

Git. In recent Python 2.7 bugfix releases, subversion

therefore contains placeholder information. It is removed in Python

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 to 0 or less, all traceback information

is suppressed and only the exception type and value are printed.

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_info and the functions provided by the

platform module.

sys.api_version¶

The C API version for this interpreter. Programmers may find this useful when

debugging version conflicts between Python and extension modules.

2.3 新版功能.

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'. The version_info value corresponding to the Python version 2.0

is (2, 0, 0, 'final', 0). The components can also be accessed by name,

so sys.version_info[0] is equivalent to sys.version_info.major

and so on.

2.0 新版功能.

在 2.7 版更改: 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.

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 the sys

module for informational purposes; modifying this value has no effect on the

registry keys used by Python. Availability: Windows.

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.

上一个主题

28. Python运行时服务

下一个主题

28.2. sysconfig — Provide access to Python’s configuration information

本页

显示源代码

快速搜索

导航

索引

模块 |

下一页 |

上一页 |

Python »

Python 2.7.18 文档 »

Python 标准库 »

28. Python运行时服务 »

© 版权所有 1990-2020, Python Software Foundation.

Python 软件基金会是一个非盈利组织。

请捐助。

Last updated on 6月 19, 2020.

发现了问题?

使用Sphinx2.3.1 创建。

python之sys模块详解 - archie’s - 博客园

python之sys模块详解 - archie’s - 博客园

会员

周边

新闻

博问

AI培训

云市场

所有博客

当前博客

我的博客

我的园子

账号设置

简洁模式 ...

退出登录

注册

登录

Archie

趁年轻,努力拚^

博客园

首页

新随笔

联系

订阅

管理

python之sys模块详解

python之sys模块详解

sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧!

sys模块的常见函数列表

sys.argv: 实现从程序外部向程序传递参数。

sys.exit([arg]): 程序中间的退出,arg=0为正常退出。

sys.getdefaultencoding(): 获取系统当前编码,一般默认为ascii。

sys.setdefaultencoding(): 设置系统默认编码,执行dir(sys)时不会看到这个方法,在解释器中执行不通过,可以先执行reload(sys),在执行 setdefaultencoding('utf8'),此时将系统默认编码设置为utf8。(见设置系统默认编码 )

sys.getfilesystemencoding(): 获取文件系统使用编码方式,Windows下返回'mbcs',mac下返回'utf-8'.

sys.path: 获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。

sys.platform: 获取当前系统平台。

sys.stdin,sys.stdout,sys.stderr: stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们

sys.argv

功能:在外部向程序内部传递参数示例:sys.py

#!/usr/bin/env python

import sys

print sys.argv[0]

print sys.argv[1]

 

运行:

# python sys.py argv1

sys.py

argv1

 

自己动手尝试一下,领悟参数对应关系

sys.exit(n)

功能:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)

示例:exit.py

#!/usr/bin/env python

import sys

def exitfunc(value):

print value

sys.exit(0)

print "hello"

try:

sys.exit(1)

except SystemExit,value:

exitfunc(value)

print "come?"

 

运行:

# python exit.py

hello

1

 

sys.path

功能:获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。

示例:

>>> import sys

>>> sys.path

['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']

 

sys.path.append("自定义模块路径")

sys.modules

功能:sys.modules是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。它拥有字典所拥有的一切方法。

示例:modules.py

#!/usr/bin/env python

import sys

print sys.modules.keys()

print sys.modules.values()

print sys.modules["os"]

 

运行:

python modules.py

['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__',......

 

sys.stdin\stdout\stderr

功能:stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们

转载:http://www.cnblogs.com/cherishry/p/5725184.html

************************************************

* 趁年轻,努力拚 *

************************************************

posted @

2017-05-16 11:03 

archie’s 

阅读(90320) 

评论(2) 

编辑 

收藏 

举报

会员力量,点亮园子希望

刷新页面返回顶部

公告

Copyright © 2024 archie’s

Powered by .NET 8.0 on Kubernetes