10. 標準庫簡短介紹¶
10.1. 作業系統介面¶
os
模組提供了數十個用於與作業系統互動的函式
>>> import os
>>> os.getcwd() # Return the current working directory
'C:\\Python313'
>>> 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()
覆蓋內建的 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'
10.2. 檔案萬用字元¶
glob
模組提供了一個函式,用於從目錄萬用字元搜尋中建立檔案列表
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
10.3. 命令列引數¶
常用的實用指令碼通常需要處理命令列引數。這些引數作為列表儲存在 sys
模組的 argv 屬性中。例如,讓我們來看一下下面的 demo.py
檔案
# File demo.py
import sys
print(sys.argv)
這是在命令列執行 python demo.py one two three
的輸出
['demo.py', 'one', 'two', 'three']
argparse
模組提供了更復雜的機制來處理命令列引數。以下指令碼提取一個或多個檔名以及要顯示的可選行數
import argparse
parser = argparse.ArgumentParser(
prog='top',
description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)
當在命令列使用 python top.py --lines=5 alpha.txt beta.txt
執行時,指令碼會將 args.lines
設定為 5
,並將 args.filenames
設定為 ['alpha.txt', 'beta.txt']
。
10.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()
。
10.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'
10.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 from the interval [0.0, 1.0)
0.17970987693706186
>>> random.randrange(6) # random integer chosen from range(6)
4
statistics
模組計算數值資料的基本統計屬性(平均值、中位數、方差等)
>>> 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> 有許多其他用於數值計算的模組。
10.7. 網際網路訪問¶
有許多模組用於訪問網際網路和處理網際網路協議。其中最簡單的兩個是 urllib.request
,用於從 URL 獲取資料,以及 smtplib
,用於傳送郵件
>>> from urllib.request import urlopen
>>> with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response:
... for line in response:
... line = line.decode() # Convert bytes to a str
... if line.startswith('datetime'):
... print(line.rstrip()) # Remove trailing newline
...
datetime: 2022-01-01T01:36:47.689215+00:00
>>> 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()
(請注意,第二個示例需要在 localhost 上執行郵件伺服器。)
10.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
10.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.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
和 pstats
模組提供了用於識別較大程式碼塊中時間關鍵部分的工具。
10.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
10.12. 內建電池¶
Python 秉持“內建電池”的理念。這一點在其大型軟體包的複雜和強大的功能中體現得淋漓盡致。例如:
xmlrpc.client
和xmlrpc.server
模組使得實現遠端過程呼叫幾乎變成了一項微不足道的任務。儘管模組的名稱如此,但無需直接瞭解或處理 XML。email
包是一個用於管理電子郵件訊息的庫,包括 MIME 和其他基於 RFC 2822 的訊息文件。與實際傳送和接收訊息的smtplib
和poplib
不同,email 包提供了一整套用於構建或解碼複雜訊息結構(包括附件)以及實現網際網路編碼和頭協議的工具集。json
包為解析這種流行的資料交換格式提供了強大的支援。csv
模組支援直接讀取和寫入逗號分隔值格式的檔案,這種格式通常為資料庫和電子表格所支援。XML 處理由xml.etree.ElementTree
、xml.dom
和xml.sax
包支援。這些模組和軟體包共同大大簡化了 Python 應用程式和其他工具之間的資料交換。sqlite3
模組是 SQLite 資料庫庫的包裝器,提供了一個持久資料庫,可以使用稍微不標準的 SQL 語法進行更新和訪問。