进阶第十二课 Python模块之sys
sys是与Python解释器交互的工具。sys模块提供了一系列有关Python运行环境的变量和函数。
先看下dir(sys)
>>> 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']
看下常用的方法:
1、sys.argv 实现从程序外部向程序传递参数。获取当前正在执行的命令行参数的参数列表(list)。
2、sys.exit(n)
功能:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)
在IDLE中按ctrl+n,打开新窗口,输入下列代码,并保存为exit.py
import sys def exitfunc(value): print(value) sys.exit(0) print("hello") try: sys.exit(1) except SystemExit,value: exitfunc(value) print("come")
在IDLE中执行
import exit hello 1
3、sys.modules
功能:sys.modules
是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules
将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。它拥有字典所拥有的一切方法。
在IDLE中按Ctrl+n打开一个新窗口,输入
import sys print(sys.modules.keys()) print(sys.modules.values()) print(sys.modules["os"])
保存为modules.py。回到IDLE中执行
import modules ['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__',......
5、sys.path
功能:获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。
>>> sys.path ['', 'C:\\Users\\Tom\\AppData\\Local\\Programs\\Python\\Python36\\Lib\\idlelib', 'C:\\Users\\Tom\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Tom\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Tom\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Tom\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Tom\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
6、sys.platform
显示当前本机的操作系统。
>>> import sys >>> sys.platform 'win32'
我的电脑室win10 64bit。大家如果有Linux的发行版操作系统,也可以试试看结果是什么。
7、sys.exit([arg])
: 程序中间的退出,arg=0为正常退出。