8.5 运行环境
sys模块是包含了Python运行环境的相关对象。
>>> 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', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']
8.5.1 sys模块的常用函数
sys.argv: 实现从程序外部向程序传递参数。sys.exit([arg]): 程序中间的退出,arg=0为正常退出。sys.getdefaultencoding(): 获取系统当前编码。sys.getfilesystemencoding(): 获取文件系统使用编码方式。sys.path: 获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。sys.platform: 获取当前系统平台。sys.stdin,sys.stdout,sys.stderr: stdin,stdout,以及stderr 变量包含与标准I/O 流对应的流对象。如果需要更好地控制输出,而print 不能满足要求时,可以替换它们,这时候就可以重定向输出和输入到其它设备( device ),或者以非标准的方式处理它们。
sys.argv
功能:在外部向程序内部传递参数
示例:8.4-sys.py
# sys模块
import sys
for arg in sys.argv:
print(arg)
结果为:
python 8.4-sys.py abc 123
8.4-sys.py
abc
123
sys.path
功能:获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。
示例:
>>> import sys
>>> sys.path
['', 'C:\\ProgramData\\Anaconda3\\python36.zip', 'C:\\ProgramData\\Anaconda3\\DLLs', 'C:\\ProgramData\\Anaconda3\\lib', 'C:\\ProgramData\\Anaconda3', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin']
如果需要添加自定义的模块,要先将模块的路径加入sys.path中:
sys.path.append("自定义模块路径")
sys.modules
功能:sys.modules是一个全局字典,该字典是Python启动后就加载在内存中。每当程序员导入新的模块,sys.modules将自动记录该模块。当第二次再导入该模块时,Python会直接到字典中查找,从而加快了程序运行的速度。它拥有字典所拥有的一切方法。
示例:
>>> import sys
>>> 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', '_bootlocale', '_locale', 'encodings.gbk', '_codecs_cn', '_multibytecodec', 'types', 'functools', '_functools', 'collections', 'operator', '_operator', 'keyword', 'heapq', '_heapq', 'itertools', 'reprlib', '_collections', 'weakref', 'collections.abc', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'warnings', 'importlib.util', 'importlib.abc', 'importlib.machinery', 'contextlib', 'mpl_toolkits', 'sphinxcontrib', 'atexit', 'time', 'datetime', 'math', '_datetime', '_strptime', 'locale', 're', 'enum', 'sre_compile', '_sre', 'sre_parse', 'sre_constants', 'copyreg', 'calendar'])
>>> sys.modules['os']
<module 'os' from 'C:\\ProgramData\\Anaconda3\\lib\\os.py'>
sys.stdin\stdout\stderr
功能:stdin,stdout,以及stderr 变量包含与标准I/O 流对应的流对象。
在需要更好的控制输出时,sys.stdout,sys.stdin可以实现。 在Python中调用print时,相当于调用了sys.stdout.write函数进行处理。