Python的sys模块提供访问由解释器使用或维护的变量的接口,并提供了一些函数用来和解释器进行交互,操控Python的运行时环境。
下面就来详细介绍下该模块中经常使用的属性和方法。python
1、导入sys模块git
import sys
2、查看sys模块的功能windows
import sys print(dir(sys))
运行结果:api
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', '_base_executable', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_git', '_home', '_xoptions', 'addaudithook', 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', '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_origin_tracking_depth', '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', 'pycache_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info', 'warnoptions', 'winver']
3、查看平台标识符字符串async
import sys print(sys.platform)
运行结果:函数
win32
4、查看当前Python解释器的版本ui
import sys print(sys.version)
运行结果:spa
3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)]
5、查看Python的环境变量或模块搜索路径命令行
import sys print(sys.path)
运行结果:debug
['D:\\python\\lianxi', 'D:\\python\\lianxi', 'D:\\Program Files\\JetBrains\\PyCharm 2020.1\\plugins\\python\\helpers\\pycharm_display']
6、查看已载入的模块
import sys print(sys.modules.keys()) # 它是返回一个字典,键是已经载入的模块名
运行结果:
dict_keys(['sys', 'builtins', '_frozen_importlib', '_imp', '_warnings', '_frozen_importlib_external', '_io', 'marshal', 'nt', '_thread', '_weakref', 'winreg', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', '_abc', 'abc', 'io', '_stat', 'stat', '_collections_abc', 'genericpath', 'ntpath', 'os.path', 'os', '_sitebuiltins', 'sitecustomize', 'site'])
7、获取正在处理的异常的相关信息
import sys try: raise KeyError # 主动抛出一个异常 except: print(sys.exc_info())
运行结果:
(<class 'KeyError'>, KeyError(), <traceback object at 0x0000020B7ABC0480>)
sys.exc_info()就是捕获到异常的信息,执行后返回一个元组,第一个元素是异常的类型,第二个是异常的消息,第三个是个对象,这个对象称为回溯对象,可是它里面有什么细节并不知道,这个时候就能够借助traceback模块来打印一下这里面的内容。
import sys import traceback try: raise KeyError except: print(sys.exc_info()) traceback.print_tb(sys.exc_info()[2])
运行结果:
(<class 'KeyError'>, KeyError(), <traceback object at 0x0000021E53E0A700>) File "D:/python/lianxi/add.py", line 4, in <module> raise KeyError
traceback.print_tb方法打印一下sys.exc_info()返回的元组里的第三个元素,因此在后面写上“[2]”,它告诉咱们你的文件在第几行哪一个模块下面有问题。
8、命令行参数
新建一个文件,存入如下代码:
import sys def add(): a = 5 b = 3 return a + b print(sys.argv) print(sys.argv[0]) print(sys.argv[1]) print(sys.argv[2])
打开windows命令行,输入:
python 文件存放路径 x y 1 2 3
格式:python+空格+文件存放路径+参数
返回值:
['D:\\python\\lianxi\\add_1.py', 'x', 'y', '1', '2', '3'] D:\python\lianxi\add_1.py x y
返回值告诉咱们整个参数有什么,第一个参数是什么,第二个参数是什么,第三个参数是什么。
9、标准输出流
import sys sys.stdout.write('Hello word')
运行结果:
Hello word
sys.stdout.write方法默认状况下等同于print。
本文转自:https://www.myblou.com/archives/1501