Python中大多数系统接口都集中在两个模块:sys和os.这么说有点过于简单化 还有一些其他的表转模块也属于这个领域他们包括:
glob 用于文件名的扩展
socket 用于网络连接和进程间通信(IPC)
threading,_threading,queue 用于运行和同步话并发线程
time,timeit 用于获取系统时间相关细节。
subprocess,multiprocessing 用于启动和控制并行进程
signal,select,shutil,tempfile 用于多种系统相关任务
还有诸如pySerial(一种串行端口接口),Pexpect(一个用于控制程序间对话的类Expect系统) 甚至TWisted(一种网络框架) 等等第三方扩展包也归入系统编程领域。另外 一些内置函数实际上也是系统接口 例如open函数 就是文件系统接口 但大体而言sys和os模块一起组成了pYthon内置系统工具的核心部分
从原则上讲 sys负责导出与python解释器本身相关的组件(如模块搜索路径) os则包含于python所在底层操作系统相对应的变量和函数 实践中这种区别并不总是这么明显(如sys包含了标准输入输出流) 但也可以说它们与操作系统模式有关
获取模块文档
学习用python来编写系统在很大程度上就是学习python的系统模块
例如我们要知道一个内置模块导出的所有东西 可以在库手册里阅读相关条目 也可以阅读它的源码 或者交互获取它的属性列表和文档字符串
我们导入ptyhon3.1sys模块 看一看它为我们提供了什么好东西
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
C:\Users\Administrator.WIN-20160322KSZ>
C:\Users\Administrator.WIN-20160322KSZ>D:
D:\>dir
驱动器 D 中的卷是 软件
卷的序列号是 000F-9CF8
D:\ 的目录
2016/07/03 21:43 6,862,200 1.zip
2016/09/14 11:17 1,325,052 code_short.pcm
2016/08/21 13:20 24 config.ini
2016/06/19 01:52 2,558 day6.py
2016/10/16 19:43 <DIR> Documents
2016/11/22 01:02 <DIR> Downloads
2016/03/21 19:45 <DIR> Favorites
2016/03/27 14:45 <DIR> kuwo
2016/11/28 23:09 <DIR> Mozilla Firefox
2016/06/21 10:52 <DIR> pdf
2016/05/15 19:16 <DIR> PP助手2.0
2016/05/02 23:02 <DIR> Program Files
2004/07/03 09:48 139,264 psicon.dll
2004/10/24 09:19 1,112 psicon.reg
2016/06/25 22:31 198,296 pyexpat.pyd
2016/05/22 20:53 <DIR> Python
2016/06/25 22:31 42,136 python.exe
2016/06/25 22:31 52,376 python3.dll
2016/06/25 22:31 3,931,288 python35.dll
2016/06/25 22:31 2,257,578 python35.zip
2016/06/25 22:31 42,136 pythonw.exe
2016/06/25 22:31 17 pyvenv.cfg
2016/10/06 13:07 <DIR> QQVipDownload
2016/11/22 15:10 <DIR> qycache
2016/06/17 15:32 <DIR> Screenshots
2016/06/25 22:31 26,264 select.pyd
2016/06/25 22:31 773,784 sqlite3.dll
2016/08/21 19:11 <DIR> Thunder Network
2016/06/25 22:31 871,576 unicodedata.pyd
2016/06/25 22:31 89,416 vcruntime140.dll
2016/02/12 13:16 <DIR> win7dock
2016/06/25 22:31 25,752 winsound.pyd
2016/06/17 22:45 <DIR> XY苹果助手
2016/06/25 22:31 91,288 _bz2.pyd
2016/06/25 22:31 129,176 _ctypes.pyd
2016/06/25 22:31 321,176 _decimal.pyd
2016/06/25 22:31 199,832 _elementtree.pyd
2016/06/25 22:31 1,444,504 _hashlib.pyd
2016/06/25 22:31 152,728 _lzma.pyd
2016/06/25 22:31 38,552 _msi.pyd
2016/06/25 22:31 28,824 _multiprocessing.pyd
2016/06/25 22:31 41,112 _overlapped.pyd
2016/06/25 22:31 72,344 _socket.pyd
2016/06/25 22:31 78,488 _sqlite3.pyd
2016/06/25 22:31 2,044,056 _ssl.pyd
2016/09/11 22:38 <DIR> 常用软件
2016/03/22 20:31 <DIR> 英雄联盟
2016/03/22 22:15 466 软件 (D).lnk
31 个文件 21,283,375 字节
17 个目录 113,867,571,200 可用字节
D:\>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loade
r__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdou
t__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
'_home', '_mercurial', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', '
base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'exc
epthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_rep
r_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'ge
tdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', '
getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion',
'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizi
ng', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'pat
h_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_coroutine_wrapper',
'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'set
trace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', '
warnoptions', 'winver']
>>>
dir函数会简单返回一个列表 其中包含了带属性队形的所有属性的字符串名称 这是一种在交互提示符下唤醒对模块的记忆便捷方式
例如dir函数结果中有version的存在 我们得一知道有一个sys.version
>>>sys.__doc__ 内置模块的__doc__字符传:返回值如下
"This module provides access to some objects used or maintained by the\ninterpre
ter and to functions that interact strongly with the interpreter.\n\nDynamic obj
ects:\n\nargv -- command line arguments; argv[0] is the script pathname if known
\npath -- module search path; path[0] is the script directory, else ''\nmodules
-- dictionary of loaded modules\n\ndisplayhook -- called to show results in an i
nteractive session\nexcepthook -- called to handle any uncaught exception other
than SystemExit\n To customize printing in an interactive session or to install
a custom\n top-level exception handler, assign other functions to replace thes
e.\n\nstdin -- standard input file object; used by input()\nstdout -- standard o
utput file object; used by print()\nstderr -- standard error object; used for er
ror messages\n By assigning other file objects (or objects that behave like fil
es)\n to these, it is possible to redirect all of the interpreter's I/O.\n\nlas
t_type -- type of last uncaught exception\nlast_value -- value of last uncaught
exception\nlast_traceback -- traceback of last uncaught exception\n These three
are only available in an interactive session after a\n traceback has been prin
ted.\n\nStatic objects:\n\nbuiltin_module_names -- tuple of module names built i
nto this interpreter\ncopyright -- copyright notice pertaining to this interpret
er\nexec_prefix -- prefix used to find the machine-specific Python library\nexec
utable -- absolute path of the executable binary of the Python interpreter\nfloa
t_info -- a struct sequence with information about the float implementation.\nfl
oat_repr_style -- string indicating the style of repr() output for floats\nhash_
info -- a struct sequence with information about the hash algorithm.\nhexversion
-- version information encoded as a single integer\nimplementation -- Python im
plementation information.\nint_info -- a struct sequence with information about
the int implementation.\nmaxsize -- the largest supported length of containers.\
nmaxunicode -- the value of the largest Unicode code point\nplatform -- platform
identifier\nprefix -- prefix used to find the Python library\nthread_info -- a
struct sequence with information about the thread implementation.\nversion -- th
e version of this interpreter as a string\nversion_info -- version information a
s a named tuple\ndllhandle -- [Windows only] integer handle of the Python DLL\nw
inver -- [Windows only] version number of the Python DLL\n__stdin__ -- the origi
nal stdin; don't touch!\n__stdout__ -- the original stdout; don't touch!\n__stde
rr__ -- the original stderr; don't touch!\n__displayhook__ -- the original displ
ayhook; don't touch!\n__excepthook__ -- the original excepthook; don't touch!\n\
nFunctions:\n\ndisplayhook() -- print an object to the screen, and save it in bu
iltins._\nexcepthook() -- print an exception and its traceback to sys.stderr\nex
c_info() -- return thread-safe information about the current exception\nexit() -
- exit the interpreter by raising SystemExit\ngetdlopenflags() -- returns flags
to be used for dlopen() calls\ngetprofile() -- get the global profiling function
\ngetrefcount() -- return the reference count for an object (plus one :-)\ngetre
cursionlimit() -- return the max recursion depth for the interpreter\ngetsizeof(
) -- return the size of an object in bytes\ngettrace() -- get the global debug t
racing function\nsetcheckinterval() -- control how often the interpreter checks
for events\nsetdlopenflags() -- set the flags to be used for dlopen() calls\nset
profile() -- set the global profiling function\nsetrecursionlimit() -- set the m
ax recursion depth for the interpreter\nsettrace() -- set the global debug traci
ng function\n"
>>>
>>>pirnt(sys.__doc__)
该模块提供了对使用或维护的一些对象的访问
解释器和与解释器交互的功能。
print()内置函数会正确地解释换行符 遗憾的是本身并不完成页面滚动或分页显示 因此在某些平台上仍会出现令人不满意的显示效果 其他工具如内置help(函数) 则做的很好
>>> help(sys)
Help on built-in module sys:
NAME
sys
MODULE REFERENCE
https://docs.python.org/3.5/library\sys.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules
-- More --
help函数是PyDoc系统提供的接口之一 PyDoc系统是python自带的标准库代码 可将对象相关的文档 呈现为格式化后的形式 这种格式化可以是类似Unix里的手册页 便于帮助使用 也是翻阅相关书籍和手册之前的最后一招。