第二章 系统编程工具

python 系统级接口都集中在两个模块,sys和os。有一些其他的模块也属于这个领域:

glob        用于文件名扩展

socket      用于网络连接和进程间通信(ipc)

threading,_thread,queue 用于运行和同步化并发线程

time,timeit    用于获取系统时间相关细节

subprocess,multiprocessing 用于启动和控制并行线程

signal, select, shutill,tempfile

用于多种系统相关任务

还有诸如pySerial(一种串行端口接口) Pexpect(一种控制程序间对话的类Expect系统),Twisted(一种网络框架)等第三方扩展包也纳入系统编程领域. 

一些内建函数也是系统接口,例如open函数

获取模块文档

Python 3.5.0 (default, Nov 17 2015, 14:40:42) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys,os
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']
>>>

dir函数用来查看模块导出的所有东西,它会返回一个列表里面包含模块所有的对象属性

还可以通过查询内置模块的_doc_字符串

>>> sys.__doc__
"This module provides access to some objects used or maintained by the\ninterpreter and to functions that interact strongly with the interpreter.\n\nDynamic objects:\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 interactive 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 these.\n\nstdin -- standard input file object; used by input()\nstdout -- standard output file object; used by print()\nstderr -- standard error object; used for error messages\n  By assigning other file objects (or objects that behave like files)\n  to these, it is possible to redirect all of the interpreter's I/O.\n\nlast_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 printed.\n\nStatic objects:\n\nbuiltin_module_names -- tuple of module names built into this interpreter\ncopyright -- copyright notice pertaining to this interpreter\nexec_prefix -- prefix used to find the machine-specific Python library\nexecutable -- absolute path of the executable binary of the Python interpreter\nfloat_info -- a struct sequence with information about the float implementation.\nfloat_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 implementation 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 -- the version of this interpreter as a string\nversion_info -- version information as a named tuple\n__stdin__ -- the original stdin; don't touch!\n__stdout__ -- the original stdout; don't touch!\n__stderr__ -- the original stderr; don't touch!\n__displayhook__ -- the original displayhook; 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 builtins._\nexcepthook() -- print an exception and its traceback to sys.stderr\nexc_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 :-)\ngetrecursionlimit() -- return the max recursion depth for the interpreter\ngetsizeof() -- return the size of an object in bytes\ngettrace() -- get the global debug tracing function\nsetcheckinterval() -- control how often the interpreter checks for events\nsetdlopenflags() -- set the flags to be used for dlopen() calls\nsetprofile() -- set the global profiling function\nsetrecursionlimit() -- set the max recursion depth for the interpreter\nsettrace() -- set the global debug tracing function\n"
>>>

分页显示文档字符串

>>> print(sys.__doc__)
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
.............

print内置函数能够正确的解释换行符。但print本身并不完成页面滚动或者分页显示,会出现令人不满意的效果

这时可以用help内置函数:

>>> help(sys)
Help on built-in module sys:
NAME
    sys
MODULE REFERENCE
    http://docs.python.org/3.5/library/sys
    
    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:
    ........

help函数时pydoc系统提供的接口之一,pydoc系统是python自带的标准库代码,可以将对象相关的文档呈现为格式化后的html页面

一个自定义分页的脚本

#!/usr/bin/env python3
"""
分隔字符串或文本并交互地进行分页
"""
def more(text,numlines=15):
    lines = text.splitlines()
    while lines:
        chunk = lines[:numlines]
        lines = lines[numlines:]
        for line in chunk: print(line)
        if lines and input('More?') not in ['y','Y']: break
if __name__=='__main__':
    import sys
    more(open(sys.argv[1]).read(),10)


字符串方法基础知识

>>> mystr='xxxxspamxxxx'
>>> mystr.find('spam')
4
>>> mystr.index('spam')
4
>>> mystr='xxaaxxaa'
>>> mystr
'xxaaxxaa'
>>> mystr.replace('aa','spam')
'xxspamxxspam'
>>> mystr
'xxaaxxaa'
>>> mystr
'xxxspamxxx'
>>> 'spam' in mystr
True
>>> 'ni' in mystr
False
>>> mystr.find('ni')
-1
>>> mystr='\tNI\n'
>>> mystr
'\tNI\n'
>>> mystr.strip()
'NI'
>>> mystr.rstrip()
'\tNI'
>>> mystr
'SHABI'
>>> mystr.lower()
'shabi'
>>> mystr.isalpha()
True
>>> mystr.isdigit()
False
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.whitespace
' \t\n\r\x0b\x0c'
>>> mystr='aaa,bbb,ccc'
>>> mystr
'aaa,bbb,ccc'
>>> mystr.split(',')
['aaa', 'bbb', 'ccc']
>>> mystr='a b\nc\nd'
>>> mystr.split()
['a', 'b', 'c', 'd']
>>> delim='NI'
>>> delim.join(['aaa','bbb','ccc'])
'aaaaNIbbbNIccc'
>>> ' '.join(['A','aaa','bbb'])
'A aaa bbb'
>>> chars=list('lorreta')
>>> chars
['l', 'o', 'r', 'r', 'e', 't', 'a']
>>> chars.append('!')
>>> ''.join(chars)
'lorreta!'
>>> >>> mystr
'xxaaxxaa'
>>> 'SPAM'.join(mystr.split('aa'))
'xxSPAMxxSPAM'


转载于:https://my.oschina.net/u/2420214/blog/596813

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值