python之sys模块

首先整理下OS模块与SYS模块的区别

  • os与sys模块的官方解释如下:
  • os: This module provides a portable way of using operating system dependent functionality.
  • 这个模块提供了一种方便的使用操作系统函数的方法。
  • sys: This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
  • 这个模块可供访问由解释器使用或维护的变量和与解释器进行交互的函数。

总结:os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口;sys模块负责程序与python解释器的交互,提供了一系列的函数和变量,用于操控python运行时的环境。

sys常用方法:

sys.argv # 命令行参数list,第一个元素是程序本身路径。
import random
import sys
# print(sys.modules.keys()) # 返回已经所有导入的模块列表
#dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 
'nt', 'winreg', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1',
'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'ntpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins',
'sysconfig', 'random', 'warnings', 'types', 'functools', '_functools', 'collections', 'operator', '_operator', 'keyword', 'heapq', '_heapq',
'itertools', 'reprlib', '_collections', 'weakref', 'collections.abc', 'math', 'hashlib', '_hashlib', '_blake2', '_sha3', 'bisect', '_bisect', '_random']) # print(sys.exit(status)) 退出程序,可以设置返回值或内容 print(sys.version) # python解释器的版本号 print(sys.platform) # 返回操作系统平台名称 sys.stdout # 标准输出 sys.stdin # 标准输入 sys.stderr # 错误输出 sys.path # 返回模块的搜索路径,初始化时使用python path环境变量的值

  

猜你喜欢

转载自www.cnblogs.com/Uncle-Guang/p/9009261.html