標籤:python
這裡對python的基礎庫做一個簡要概述,包括每個模組的準系統和常用操作。更詳細的資訊請參考Python庫參考。
作業系統介面
作業系統介面對應os模組,用於與作業系統互動:
>>> import os>>> os.getcwd() # 返回當前的工作目錄'C:\\Python34'>>> os.chdir('/server/accesslogs') # 改變當前工作目錄>>> os.system('mkdir today') # 運行系統命令mkdir0注意使用import os匯入os模組,不要使用from os import *,防止os.open()和內建函數open()衝突。
內建函數dir()和help()可以協助使用os這樣的大模組:
>>> import os>>> dir(os)<返回所有模組方法的列表>>>> help(os)<返回模組的手冊,該手冊來自模組的docstrings>
對於日常檔案和檔案夾管理工作,shutil模組提供了更易用的更高層次的介面。
>>> import shutil>>> shutil.copyfile('data.db', 'archive.db')'archive.db'>>> shutil.move('/build/executables', 'installdir')'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']
getopt模組使用Unix的getopt()函數處理sys.argv。更多強大的和可擴充的命令列處理函數被argparse模組提供。
錯誤輸出重新導向和程式終止
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模組提供了Regex工具,對於複雜的字串匹配和處理,Regex提供了簡潔的、最優的解決方案:
>>> 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'
當今需要簡單的功能時,string的方法是更好的,因為他們更加易於理解和閱讀:
>>> '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
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 float0.17970987693706186>>> random.randrange(6) # random integer chosen from range(6)4
SciPy項目<http://scipy.org>為數字計算提供了多個模組。
網路
有多個模組用於串連internet和處理internet協議。其中最簡單的兩個是urllib.request(用於從URL擷取資料)和smtplib(發送郵件):
>>> from urllib.request import urlopen>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): line = line.decode('utf-8') # 解碼位元據到文本 if 'EST' in line or 'EDT' in line: 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()注意第二個例子需要一個郵件伺服器運行在localhost。
日期和時間
datetime模組提供類處理日期和時間。日期和時間的演算法主要聚焦在為輸出格式化和處理。該模組也支援時區。
>>> # dates are easily constructed and formatted>>> from datetime import date>>> now = date.today()>>> nowdatetime.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.days14368
資料壓縮
支援通常的資料歸檔和壓縮格式,包括模組: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
效率測試
一些使用者對於效率問題非常關注,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和pstats模組提供了為大塊代碼做效率測試的工具。
品質控制
開發高品質軟體的一個方法是為每個函數寫測試,並在開發的過程中頻繁的執行這些測試。
doctest模組提供了工具,用於掃描一個模組並驗證嵌入在程式的docstring中的測試。測試是儘可能簡單的語句,並包含它的結果。
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 doctestdoctest.testmod() # automatically validate the embedded testsunittest模組要比doctest複雜,它允許在一個單獨的檔案中寫一整套測試:import unittestclass 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
python17:基礎庫概述