10. 標準庫簡要介紹

10.1. 作業系統介面

os 模組提供了數十個用於與作業系統互動的函式。

>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python314'
>>> 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 模組還具有 stdinstdoutstderr 屬性。後者對於發出警告和錯誤訊息非常有用,即使 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. 網際網路訪問

有許多模組用於訪問網際網路和處理網際網路協議。其中最簡單的兩個是用於從 URL 檢索資料的 urllib.request 和用於傳送郵件的 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. 資料壓縮

模組直接支援常見的資料歸檔和壓縮格式,包括:zlibgzipbz2lzmazipfiletarfile

>>> 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 的精細粒度不同,profilepstats 模組提供了用於識別較大程式碼塊中時間關鍵部分的工具。

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.clientxmlrpc.server 模組使得實現遠端過程呼叫幾乎成為一項微不足道的任務。儘管模組名稱如此,但不需要直接瞭解或處理 XML。

  • email 包是一個用於管理電子郵件訊息的庫,包括 MIME 和其他基於 RFC 2822 的訊息文件。與實際傳送和接收訊息的 smtplibpoplib 不同,email 包擁有完整的工具集,用於構建或解碼複雜的訊息結構(包括附件),以及實現網際網路編碼和頭部協議。

  • json 包提供了對解析這種流行資料交換格式的強大支援。csv 模組支援直接讀取和寫入逗號分隔值格式的檔案,這種格式通常受資料庫和電子表格支援。XML 處理由 xml.etree.ElementTreexml.domxml.sax 包支援。這些模組和包共同大大簡化了 Python 應用程式與其他工具之間的資料交換。

  • sqlite3 模組是 SQLite 資料庫庫的包裝器,提供了一個永續性資料庫,可以使用略微非標準的 SQL 語法進行更新和訪問。

  • 國際化由許多模組支援,包括 gettextlocalecodecs 包。