最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python——必会内置模块 Sys
时间:2026-07-17 09:12:50 编辑:袖梨 来源:一聚教程网
Sys 系统相关的形参和函数
命令行参数
sys.argv是一个包含了所有传递给 python 脚本命令行参数的列表
复制代码import sysprint("argv[0]:", sys.argv[0])
# argv[0]代表了脚本自身的名称print("argv[1]:", sys.argv[1])
# argv[1]代表了脚本的第一个参数
- 我们在命令行中运行脚本,在脚本后面给一个参数,就可以用
sys.argv来获取

编译器信息
复制代码import sysprint('Version info:')
print()
print('sys.version =', repr(sys.version))
print('sys.version_info =', sys.version_info)
print('sys.hexversion =', hex(sys.hexversion))
print('sys.api_version =', sys.api_version)
# 输出python解释器版本的相关信息print('This interpreter was built for:', sys.platform)
# 解释器是基于什么操作系统构建的print('Name:', sys.implementation.name)
print('Version:', sys.implementation.version)
print('Cache tag:', sys.implementation.cache_tag)
# 解释器是基于什么实现的print('Default encoding :', sys.getdefaultencoding())
print('File system encoding :', sys.getfilesystemencoding())
# 解释器的默认编码格式和文件系统的编码格式print('Interpreter executable:')
print(sys.executable)
print('nInstallation prefix:')
print(sys.prefix)
# 输出解释器的安装路径
- 当我们使用交互式解释器时,我们甚至可以通过 sys 的参数来修改提示符默认提示符

- 我们现在一个 py 文件中定义一个类,来创建我们的提示符样式
复制代码class LineCounter:
def __init__(self):
self.count = 0
def __str__(self):
self.count += 1
return "({:3d})>".format(self.count)
# 用作提示字符串的样式
- 然后在终端中,导入这个模块的类,用它来代替原本的
sys.ps1,终端的提示符就会改变终端提示符

内存管理
- Python 的内存管理由引用计数+垃圾回收机制组成。当一个内存数据被变量所引用的次数为 0 时,这个数据所在的内存空间会被清除
复制代码import sysone = []
print('At start :', sys.getrefcount(one))two = one
print('Second reference :', sys.getrefcount(one))del two
print('After del :', sys.getrefcount(one))
- 输出结果是 2、3、2,这是因为对
getrefcount()自身存在着引用,所以计数会多 1,实际上的引用计数是 1、2、1 - 我们也可以用
getsizeof查询数据所占的内存空间
复制代码import sysclass MyClass:
passobjects = [
[], (), {}, 'c', 'string', b'bytes', 1, 2.3,
MyClass, MyClass(),
]
for obj in objects:
print('{:>10} : {}'.format(type(obj).__name__, sys.getsizeof(obj)))
- 结果(并未包含属性值可能占用的内存)

- 为了避免递归导致的内存溢出,我们可以查询或更改限制递归的次数
复制代码import sysprint('Initial limit:', sys.getrecursionlimit())
# 获取初始的递归深度
sys.setrecursionlimit(10)
# 设置递归深度
print('Modified limit:', sys.getrecursionlimit())
def generate_recursion_error(i):
print('generate_recursion_error({})'.format(i))
generate_recursion_error(i + 1)
try:
generate_recursion_error(1)
except RuntimeError as err:
print('Caught exception:', err)
# 可以发现当我们更改完递归深度后,在第十次递归后报错
- 我们也可以查询内存所支持的各个类型值的最大值
复制代码import sysprint('maxsize :', sys.maxsize)
# 列表、字典、字符串等数据结构的最大长度
print('maxunicode:', sys.maxunicode)
# 支持的最大Unicode整数
print('Smallest difference (epsilon):', sys.float_info.epsilon)
# 最小的差值
print('Maximum (max):', sys.float_info.max)
print('Minimum (min):', sys.float_info.min)
# 最大浮点数和最小浮点数
print('Maximum exponent for radix (max_exp):',
sys.float_info.max_exp)
print('Minimum exponent for radix (min_exp):',
sys.float_info.min_exp)
# 指数的最大和最小值
print('Max. exponent power of 10 (max_10_exp):',
sys.float_info.max_10_exp)
print('Min. exponent power of 10 (min_10_exp):',
sys.float_info.min_10_exp)
# 科学计数法也就是10的指数幂的最大和最小值
print('Number of bits used to hold each digit:',
sys.int_info.bits_per_digit)
# 保存每个数字的位数
print('Size in bytes of C type used to hold each digit:',
sys.int_info.sizeof_digit)
# 保存每个数字的C类型字节大小
模块查询
- 当我们需要知道某个 python 文件导入了哪些模块时,我们可以用
sys.modules来查询
复制代码import sysnames = sorted(sys.modules.keys())
print(names)
# 输出所有导入的模块,包含了内置模块
# ['__main__', '_abc', '_codecs', '_codecs_cn', '_collections_abc', '_frozen_importlib', '_frozen_importlib_external', '_imp', '_io', '_multibytecodec', '_signal', '_sitebuiltins', '_stat', '_thread', '_warnings', '_weakref', '_winapi', 'abc', 'builtins', 'codecs', 'encodings', 'encodings._win_cp_codecs', 'encodings.aliases', 'encodings.gbk', 'encodings.utf_8', 'errno', 'genericpath', 'marshal', 'nt', 'ntpath', 'os', 'os.path', 'site', 'stat', 'sys', 'time', 'winreg', 'zipimport']
print(sys.builtin_module_names)
# 只输出内置模块
for d in sys.path:
print(d)
# 模块的导入路径,第一个路径时脚本本身所在目录