第二章 系統編程工具

python 系統級接口都集中在兩個模塊,sys和os。有一些其餘的模塊也屬於這個領域:
html

glob        用於文件名擴展python

socket      用於網絡鏈接和進程間通訊(ipc)linux

threading,_thread,queue 用於運行和同步化併發線程git

time,timeit    用於獲取系統時間相關細節編程

subprocess,multiprocessing 用於啓動和控制並行線程api

signal, select, shutill,tempfile網絡

用於多種系統相關任務session

還有諸如pySerial(一種串行端口接口) Pexpect(一種控制程序間對話的類Expect系統),Twisted(一種網絡框架)等第三方擴展包也歸入系統編程領域. 併發

一些內建函數也是系統接口,例如open函數app

獲取模塊文檔

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'
相關文章
相關標籤/搜索