[譯]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 *
。后者會(huì)導(dǎo)入os.open()
并屏蔽效率更高的內(nèi)置函數(shù)open
。
使用如os
一般的大型模塊時(shí),內(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>
對(duì)于日常文件和目錄的管理任務(wù),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ù)作為列表存儲(chǔ)在sys
模塊的argv屬性中。例如以下是在命令行運(yùn)行python demo.py one two three
輸出結(jié)果:
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
getopt
模塊使用Unix的getopt()
函數(shù)約定處理sys.argv。更多強(qiáng)大并靈活的命令行處理由argparse模塊提供。
10.4 Error Output Redirection and Program Termination
sys
模塊擁有變量stdin,stdout以及stderr。當(dāng)stdout被重定向時(shí),后者也發(fā)出打印警告和錯(cuò)誤信息并且使其可見(jiàn):
>>> 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
模塊為高級(jí)字符串處理提供了正則表達(dá)式。對(duì)于復(fù)雜的匹配和操作,正則表達(dá)式提供了簡(jiǎn)潔有效的解決方案:
>>> 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'
若只需要簡(jiǎn)單功能,推薦使用字符串方法,因?yàn)槠涓涌勺x以及便于調(diào)試:
>>> 'tea for too'.replace('too', 'two')
'tea for two'
10.6 Mathematics
math
模塊為浮點(diǎn)數(shù)學(xué)計(jì)算提供了對(duì)底層C庫(kù)函數(shù)的訪問(wèn):
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
random
模塊提供了生成隨機(jī)序列的工具:
>>> 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
模塊提供了計(jì)算數(shù)字?jǐn)?shù)據(jù)基礎(chǔ)統(tǒng)計(jì)屬性(如均值,中位數(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 項(xiàng)目 https://scipy.org 提供了許多用于數(shù)字計(jì)算的模塊
10.7 Internet Access
Python提供了許多用于網(wǎng)絡(luò)資源訪問(wèn)以及互聯(lián)網(wǎng)協(xié)議處理的模塊。最簡(jiǎn)單的兩個(gè)是用于從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()
(注意第二個(gè)示例需要在本地運(yùn)行的郵件服務(wù))
10.8 Dates and Times
datetime
模塊提供了以簡(jiǎn)單或者復(fù)雜方式計(jì)算時(shí)間以及日期的類(lèi)。支持日期和時(shí)間算法的同時(shí),實(shí)現(xiàn)的重點(diǎn)放在更有效的處理和格式化輸出。該模塊同時(shí)支持時(shí)區(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開(kāi)發(fā)者對(duì)同一個(gè)問(wèn)題的不同解決方案的相對(duì)性能有極大興趣。Python為此提供了一個(gè)測(cè)量工具。
例如,使用元組的打包和解包特性代替?zhèn)鹘y(tǒng)方法實(shí)現(xiàn)值的交換是很誘人的。timeit
模塊能夠快速證實(shí)序列解包更快:
>>> 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
的細(xì)粒度,profile
以及pstas
模塊提供了適用于大型代碼塊的性能測(cè)量工具。
10.11 Quality Control
開(kāi)發(fā)高質(zhì)量軟件的一種方式是在每一個(gè)函數(shù)編寫(xiě)時(shí),為其編寫(xiě)測(cè)試用例,并且在開(kāi)發(fā)過(guò)程中經(jīng)常運(yùn)行這些測(cè)試用例。
doctest
模塊提供了一個(gè)工具,該工具掃描模塊并驗(yàn)證內(nèi)嵌入程序文檔字符串中的測(cè)試。測(cè)試的結(jié)構(gòu)非常簡(jiǎn)單,就像復(fù)制粘貼一個(gè)附帶返回值的典型函數(shù)調(diào)用一樣。為使用者提供調(diào)用示例,從而增強(qiáng)了文檔,同時(shí)允許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模塊那樣簡(jiǎn)單,但是它允許在單獨(dú)的文件中維護(hù)復(fù)雜的測(cè)試集合:
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有“自帶電池”的哲學(xué)。這一點(diǎn)可以從Python自帶龐大包提供的大量功能看出來(lái)。例如:
-
xmlrpc.server和
xmlrpc.client
模塊讓遠(yuǎn)程調(diào)用變得非常簡(jiǎn)單,盡管名字中有xml,但是在使用時(shí)無(wú)需xml的知識(shí),也不需要處理xml。 -
email包是管理郵件信息的庫(kù),包括MIME其他以及基于RFC-32的信息文檔。與實(shí)際發(fā)送和接受郵件的
smtplib
和poplib
不同,emial包擁有一個(gè)完整的工具集合,該工具集包含構(gòu)造以及解碼復(fù)雜消息結(jié)構(gòu)(包括附件)以及實(shí)現(xiàn)網(wǎng)絡(luò)編碼和頭協(xié)議等功能。 - json包提供了解析json這種流行的數(shù)據(jù)交換格式的支持。csv支持直接讀寫(xiě)通用數(shù)據(jù)格式文件,包括數(shù)據(jù)庫(kù)和表格文件。xml.etree.ElementTree, xml.dom 以及 xml.sax包支持XML的處理。這些模塊極大簡(jiǎn)化了Python應(yīng)用和其他工具之間的數(shù)據(jù)交換。
- sqlite3模塊是對(duì)SQLite數(shù)據(jù)庫(kù)的包裝庫(kù),該模塊提供了一個(gè)持久數(shù)據(jù)庫(kù),可以通過(guò)稍微不標(biāo)準(zhǔn)的sql語(yǔ)法訪問(wèn)和更新數(shù)據(jù)庫(kù)。
- 國(guó)際化由一系列模塊支持,包括: gettext, locale, 以及codecs包。