Python3標準庫
操作系統接口
os模塊提供了不少與操作系統相關聯的函數。
>>> import os>>> os.getcwd()   # 返回當前的工作目錄'C://Python34'>>> os.chdir('/server/accesslogs')  # 修改當前的工作目錄>>> os.system('mkdir today')  # 執行系統命令 mkdir 0建議使用 "import os" 風格而非 "from os import *"。這樣可以保證隨操作系統不同而有所變化的 os.open() 不會覆蓋內置函數 open()。
在使用 os 這樣的大型模塊時內置的 dir() 和 help() 函數非常有用:
>>> import os>>> dir(os)<returns a list of all module functions>>>> help(os)<returns an extensive manual page created from the module's docstrings>
針對日常的文件和目錄管理任務,:mod:shutil 模塊提供了一個易于使用的高級接口:
>>> import shutil>>> shutil.copyfile('data.db', 'archive.db')>>> shutil.move('/build/executables', 'installdir')文件通配符
glob模塊提供了一個函數用于從目錄通配符搜索中生成文件列表:
>>> import glob>>> glob.glob('*.py')['primes.py', 'random.py', 'quote.py']命令行參數
通用工具腳本經常調用命令行參數。這些命令行參數以鏈表形式存儲于 sys 模塊的 argv 變量。例如在命令行中執行 "python demo.py one two three" 后可以得到以下輸出結果:
>>> import sys>>> print(sys.argv)['demo.py', 'one', 'two', 'three']
錯誤輸出重定向和程序終止
sys 還有 stdin,stdout 和 stderr 屬性,即使在 stdout 被重定向時,后者也可以用于顯示警告和錯誤信息。
>>> sys.stderr.write('Warning, log file not found starting a new one/n')Warning, log file not found starting a new one大多腳本的定向終止都使用 "sys.exit()"。
字符串正則匹配
re模塊為高級字符串處理提供了正則表達式工具。對于復雜的匹配和處理,正則表達式提供了簡潔、優化的解決方案:
>>> import re>>> re.findall(r'/bf[a-z]*', 'which foot or hand fell fastest')['foot', 'fell', 'fastest']>>> re.sub(r'(/b[a-z]+) /1', r'/1', 'cat in the the hat')'cat in the hat'
如果只需要簡單的功能,應該首先考慮字符串方法,因為它們非常簡單,易于閱讀和調試:
>>> 'tea for too'.replace('too', 'two')'tea for two'數學
math模塊為浮點運算提供了對底層C函數庫的訪問:
>>> import math>>> math.cos(math.pi / 4)0.70710678118654757>>> math.log(1024, 2)10.0
新聞熱點
疑難解答