Sys 系统相关的形参和函数
命令行参数
sys.argv 是一个包含了所有传递给 python 脚本命令行参数的列表
复制代码import sysprint("argv[0]:", sys.argv[0])
print("argv[1]:", sys.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)
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)
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)
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)
模块查询
- 当我们需要知道某个 python 文件导入了哪些模块时,我们可以用
sys.modules 来查询
复制代码import sysnames = sorted(sys.modules.keys())
print(names)
print(sys.builtin_module_names)
for d in sys.path:
print(d)