Python内置模块sys
sys模块代表了Python解释器相关有的信息,主要用来获取解释器的信息。下面的方法提供查看sys模块下的全部程序单元(包括变量和函数等):
>>> import sys
>>> [elem for elem in dir(sys) if not elem.startswith('_')]
['abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix',
'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
'get_coroutine_wrApper', 'getallocatedblocks', 'getcheckinterval',
'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodeerrors',
'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount',
'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion',
'implementation', 'int_info', 'intern', 'is_finalizing', 'last_traceback',
'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules',
'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2',
'real_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth',
'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile',
'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin',
'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']
可以看出,sys模块提供了大量的属性和函数,由于有一些功能方法在实际程序开发中用的并不多,下面仅介绍常用的属性和函数。
命令行参数与argv列表元素的对应关系
# 新建文件argv_test.py, 代码内容如下
import sys
# 输入argv列表的长度
print(f'argv列表的长度为:{len(sys.argv)}')
# 打印argv的元素
for arg in sys.argv:
print(arg)
# 使用下面命令执行该文件
$ python argv_test.py fengqinyang duguqiubai dongfangbubai renwoxing
# 输出
argv列表的长度为:5
argv_test.py
fengqinyang
duguqiubai
dongfangbubai
renwoxing
>>> print(sys.copyright)
Copyright (c) 2001-2019 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
>>> print(sys.executable)
/Users/david.tian/.virtualenvs/pysparkvenv/bin/python
>>> print(sys.getfilesystemencoding())
utf-8
>>> print(sys.getrefcount(sys))
57
>>> myfullname = 'davidekaka'
>>> print(sys.getrefcount(myfullname))
2
>>> print(sys.getrecursionlimit())
1000
>>> sys.setrecursionlimit(1100)
>>> print(sys.getrecursionlimit())
1100
>>> sys.setrecursionlimit(1000)
>>> print(sys.maxsize)
9223372036854775807
>>> print(sys.version)
3.7.4 (v3.7.4:e09359112e, Jul 8 2019, 14:54:52)
[Clang 6.0 (clang-600.0.57)]
>>> print(sys.platform)
darwin
>>> print(sys.path)
['', '/Users/david.tian/.virtualenvs/pysparkvenv/lib/python37.zip',
'/Users/david.tian/.virtualenvs/pysparkvenv/lib/python3.7',
'/Users/david.tian/.virtualenvs/pysparkvenv/lib/python3.7/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Users/david.tian/.virtualenvs/pysparkvenv/lib/python3.7/site-packages']