1. 操作系統介面 os 模塊提供很多函數與操作系統進行交互︰ 確保使用import os而不是from os import *。這樣可以防止函數os.open()覆蓋內建函數open(),兩者之間的操作是很不同的。內建函數dir()和help()對os這樣的大型模塊提供互動式的幫助是很有用的: 對 ...
1. 操作系統介面
os 模塊提供很多函數與操作系統進行交互︰
>>> import os >>> os.getcwd() # 返回當前的工作目錄 'C:\\Python35' >>> os.chdir('/server/accesslogs') # 修改當前的工作目錄 >>> os.system('mkdir today') # 執行系統命令 mkdir 0
確保使用import os而不是from os import *。這樣可以防止函數os.open()覆蓋內建函數open(),兩者之間的操作是很不同的。
內建函數dir()和help()對os這樣的大型模塊提供互動式的幫助是很有用的:
>>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive manual page created from the module's docstrings>
對於日常的文件和目錄管理任務, 這 shutil 模塊提供了一個簡單好用的高級介面:
>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') 'archive.db' >>> shutil.move('/build/executables', 'installdir') 'installdir'
2. 文件通配符
glob模塊提供一個對目錄中的文件進行通配符搜索的函數:
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py']
3. 命令行參數
常見的實用程式腳本通常需要處理命令行參數。那些參數以列表的形式存儲在sys 模塊的 argv 屬性中.例如下麵在命令行中運行python demo.py one two three 的輸出結果:
>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three']
getopt 模塊處理sys.argv u時使用 getopt() 函數的約定。argparse 模塊提供更加靈活和強大的命令行處理。
4. 錯誤輸出重定向和程式終止
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()
5. 字元串模板匹配
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'
6. 數學
math模塊提供基於c庫函數的浮點運算.
>>> import math >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0
random 的模塊提供了進行隨機選擇的工具︰
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4
statistics 模塊計算數值數據的基本統計特性 (均值、 中位數、 方差,等)。e :
>>> import statistics >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> statistics.mean(data) 1.6071428571428572 >>> statistics.median(data) 1.25 >>> statistics.variance(data) 1.3720238095238095
SciPy 項目 https://scipy.org 有數值計算的許多其他模塊。
7. 互聯網訪問(3.5.2urllib中無request 屬性)
有很多的模塊用於訪問互聯網和處理的互聯網協議。最簡單的兩個是用於網路訪問的 urllib.request 和用於發送郵件的 smtplib
>>> from urllib.request import urlopen >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response: ... for line in response: ... line = line.decode('utf-8') # Decoding the binary data to text. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print(line) <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('[email protected]', '[email protected]', ... """To: [email protected] ... From: [email protected] ... ... Beware the Ides of March. ... """) >>> server.quit()
(請註意第二個示例需要在本地主機上運行郵件伺服器)。
8. 日期和時間
datetime模塊提供了處理日期和時間的簡單和複雜的方法。支持日期和時間演算法的同時,實現的重點放在更有效的處理和格式化輸出。該模塊還支持處理時區。
>>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368
9. 數據壓縮
通常的數據歸檔和壓縮格式由以下模塊直接支持,包括:zlib,gzip,bz2,lzma zipfile和tarfile。
>>> import zlib >>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979
10. 性能測量
一些 Python 用戶對同一問題的不同解決方法之間的性能差異深有興趣。Python 提供了的一個度量工具可以立即解決這些問題。
例如,使用元組封裝和拆封功能而不是傳統的方法來交換參數可能會更吸引人。timeit模塊能夠快速演示一個適度的性能優勢:
>>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791
與timeit的精細粒度相對比,profile and pstats 模塊提供了識別時間跨度較大的代碼的工具。
11. 質量控制
開發高質量軟體的方法之一是為每一個函數編寫測試代碼,並且在開發過程中經常性的運行這些測試代碼。
doctest模塊為 掃描模塊 和 驗證測試 提供了一個嵌入程式文檔中的工具。測試的構造像一個把結果剪切並粘貼到文檔字元串的典型調用一樣簡單。通過用戶提供的例子,它發展了文檔,允許 doctest 模塊確認代碼的結果是否與文檔一致:
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests
unittest模塊並不像doctest模塊那麼輕鬆,但它允許在單獨的文件中維護一組更全面的測試:
import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main() # Calling from the command line invokes all tests
12. Batteries Included
Python 有"Batteries Included"的哲學。這最好是通過其較大的文件包的先進和強大功能。例如:
- xmlrpc.client和xmlrpc.server模塊使得實現遠程過程調用成為一個非常簡單的任務。儘管模塊名稱包含XML,但不需要直接瞭解或處理XML。
- email包是用於管理電子郵件(包括MIME和其他基於RFC 2822的郵件文檔)的庫。與實際發送和接收郵件的smtplib和poplib不同,email包有一個完整的工具集,用於構建或解碼複雜的郵件結構(包括附件)和實現互聯網編碼和頭協議。
- json包為解析這種流行的數據交換格式提供了強大的支持。csv模塊支持以逗號分隔值格式直接讀取和寫入文件,通常由資料庫和電子錶格支持。XML處理由xml.etree.ElementTree,xml.dom和xml.sax包支持。這些模塊和包一起大大簡化了 Python 應用程式和其他工具之間的數據交換。
- sqlite3模塊是SQLite資料庫庫的包裝器,提供可以使用稍微非標準的SQL語法進行更新和訪問的持久性資料庫。
- 國際化由許多模塊支持,包括gettext、locale和編解碼器包。