[譯]The Python Tutorial#Brief Tour of the Standard Library
10.1 Operating System Interface
os模塊為與操作系統(tǒng)交互提供了許多函數(shù):
>>> import os
>>> os.getcwd() # Return the current working directory
'C:\\Python36'
>>> os.chdir('/server/accesslogs') # Change current working directory
>>> os.system('mkdir today') # Run the command mkdir in the system shell
0
確保使用import os
而不是from os import *
宫仗。后者會導入os.open()
并屏蔽效率更高的內(nèi)置函數(shù)open
绊率。
使用如os
一般的大型模塊時厉颤,內(nèi)置函數(shù)dir()
和help()
函數(shù)提供的交互式幫助很有用:
>>> 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'
10.2 File Wildcards
glob
模塊提供了函數(shù)饺窿,該函數(shù)在指定目錄下使用通配符搜索文件鲫咽,并返回符合的文件名列表:
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
10.3 Command Line Arguments
一般的工具腳本通常需要處理命令行參數(shù)姨伤。命令行參數(shù)作為列表存儲在sys
模塊的argv屬性中。例如以下是在命令行運行python demo.py one two three
輸出結(jié)果:
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
getopt
模塊使用Unix的getopt()
函數(shù)約定處理sys.argv贩幻。更多強大并靈活的命令行處理由argparse模塊提供轿腺。
10.4 Error Output Redirection and Program Termination
sys
模塊擁有變量stdin,stdout以及stderr丛楚。當stdout被重定向時族壳,后者也發(fā)出打印警告和錯誤信息并且使其可見:
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
終止腳本最直接的方式是使用sys.exit()
。
10.5 String Pattern Matching
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'
若只需要簡單功能,推薦使用字符串方法,因為其更加可讀以及便于調(diào)試:
>>> 'tea for too'.replace('too', 'two')
'tea for two'
10.6 Mathematics
math
模塊為浮點數(shù)學計算提供了對底層C庫函數(shù)的訪問:
>>> 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
模塊提供了計算數(shù)字數(shù)據(jù)基礎(chǔ)統(tǒng)計屬性(如均值赖歌,中位數(shù),方差等)的方法:
>>> 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 提供了許多用于數(shù)字計算的模塊
10.7 Internet Access
Python提供了許多用于網(wǎng)絡(luò)資源訪問以及互聯(lián)網(wǎng)協(xié)議處理的模塊功茴。最簡單的兩個是用于從URL獲取數(shù)據(jù)的urllib.request庐冯,以及發(fā)送郵件的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('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()
(注意第二個示例需要在本地運行的郵件服務)
10.8 Dates and Times
datetime
模塊提供了以簡單或者復雜方式計算時間以及日期的類。支持日期和時間算法的同時坎穿,實現(xiàn)的重點放在更有效的處理和格式化輸出展父。該模塊同時支持時區(qū)處理。
>>> # 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
10.9 Data Compression
以下模塊直接支持通用數(shù)據(jù)的打包和壓縮格式: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.10 Performance Measurement
一些Python開發(fā)者對同一個問題的不同解決方案的相對性能有極大興趣玲昧。Python為此提供了一個測量工具栖茉。
例如,使用元組的打包和解包特性代替?zhèn)鹘y(tǒng)方法實現(xiàn)值的交換是很誘人的孵延。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
以及pstas
模塊提供了適用于大型代碼塊的性能測量工具。
10.11 Quality Control
開發(fā)高質(zhì)量軟件的一種方式是在每一個函數(shù)編寫時尘应,為其編寫測試用例惶凝,并且在開發(fā)過程中經(jīng)常運行這些測試用例。
doctest
模塊提供了一個工具犬钢,該工具掃描模塊并驗證內(nèi)嵌入程序文檔字符串中的測試苍鲜。測試的結(jié)構(gòu)非常簡單,就像復制粘貼一個附帶返回值的典型函數(shù)調(diào)用一樣玷犹。為使用者提供調(diào)用示例混滔,從而增強了文檔,同時允許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
10.12 Batteries Included
Python有“自帶電池”的哲學坯屿。這一點可以從Python自帶龐大包提供的大量功能看出來。例如:
-
xmlrpc.server和
xmlrpc.client
模塊讓遠程調(diào)用變得非常簡單晴股,盡管名字中有xml愿伴,但是在使用時無需xml的知識,也不需要處理xml电湘。 -
email包是管理郵件信息的庫隔节,包括MIME其他以及基于RFC-32的信息文檔。與實際發(fā)送和接受郵件的
smtplib
和poplib
不同寂呛,emial包擁有一個完整的工具集合怎诫,該工具集包含構(gòu)造以及解碼復雜消息結(jié)構(gòu)(包括附件)以及實現(xiàn)網(wǎng)絡(luò)編碼和頭協(xié)議等功能。 - json包提供了解析json這種流行的數(shù)據(jù)交換格式的支持贷痪。csv支持直接讀寫通用數(shù)據(jù)格式文件幻妓,包括數(shù)據(jù)庫和表格文件。xml.etree.ElementTree, xml.dom 以及 xml.sax包支持XML的處理劫拢。這些模塊極大簡化了Python應用和其他工具之間的數(shù)據(jù)交換肉津。
- sqlite3模塊是對SQLite數(shù)據(jù)庫的包裝庫强胰,該模塊提供了一個持久數(shù)據(jù)庫,可以通過稍微不標準的sql語法訪問和更新數(shù)據(jù)庫妹沙。
- 國際化由一系列模塊支持偶洋,包括: gettext, locale, 以及codecs包。