sys 模塊主要負責與 Python 解釋器進行交互,該模塊提供了一系列用于控制 Python 運行環(huán)境的函數(shù)和變量。
之前我們說過 os 模塊,該模塊與 sys 模塊從名稱上看著好像有點類似,實際上它們之間是沒有什么關(guān)系的,os 模塊主要負責與操作系統(tǒng)進行交互。
我們先整體看一下 sys 模塊都包含哪些內(nèi)容,如下所示:
>>> 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']
對于一些相對常用的變量和函數(shù),我們下面再來具體看一下。
argv
返回傳遞給 Python 腳本的命令行參數(shù)列表??聪率纠?/p>
import sysif __name__ == '__main__': args = sys.argv print(args) print(args[1])
上面文件名為:test.py,我們在控制臺使用命令:python test.py 123 abc
執(zhí)行一下,執(zhí)行結(jié)果如下:
['test.py', '123', 'abc']123
version
返回 Python 解釋器的版本信息。
winver
返回 Python 解釋器主版號。
platform
返回操作系統(tǒng)平臺名稱。
path
返回模塊的搜索路徑列表。
maxsize
返回支持的最大整數(shù)值。
maxunicode
返回支持的最大 Unicode 值。
copyright
返回 Python 版權(quán)信息。
modules
以字典類型返回系統(tǒng)導(dǎo)入的模塊。
byteorder
返回本地字節(jié)規(guī)則的指示器。
executable
返回 Python 解釋器所在路徑。
import sysprint(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
標準輸出??聪率纠?/p>
import sys# 下面兩行代碼等價sys.stdout.write('Hi' + '\n')print('Hi')
stdin
標準輸入??聪率纠?/p>
import syss1 = input()s2 = sys.stdin.readline()print(s1)print(s2)
stderr
錯誤輸出??聪率纠?/p>
import syssys.stderr.write('this is a error message')
exit()
退出當前程序??聪率纠?/p>
import sysprint('Hi')sys.exit()print('Jhon')
getdefaultencoding()
返回當前默認字符串編碼的名稱。
getrefcount(obj)
返回對象的引用計數(shù)。
getrecursionlimit()
返回支持的遞歸深度。
getsizeof(object[, default])
以字節(jié)為單位返回對象的大小。
setswitchinterval(interval)
設(shè)置線程切換的時間間隔。
getswitchinterval()
返回線程切換時間間隔。
import sysprint(sys.getdefaultencoding())print(sys.getrefcount('123456'))print(sys.getrecursionlimit())print(sys.getsizeof('abcde'))sys.setswitchinterval(1)print(sys.getswitchinterval())