### 10. 標準庫概覽
### 10.1. 操作系統接口
[os](# "os: Miscellaneous operating system interfaces.")模塊提供了幾十個函數與操作系統交互:
~~~
>>> import os
>>> os.getcwd() # Return the current working directory
'C:\\Python34'
>>> os.chdir('/server/accesslogs') # Change current working directory
>>> os.system('mkdir today') # Run the command mkdir in the system shell
0
~~~
一定要使用importos的形式而不要用fromosimport*。這將避免[os.open()](# "os.open")屏蔽內置的[open()](# "open")函數,它們的功能完全不同。
內置的[dir()](# "dir")和[help()](# "help")函數對于使用像[os](# "os: Miscellaneous operating system interfaces.")大型模塊可以作為非常有用的交互式幫助:
~~~
>>> 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](# "shutil: High-level file operations, including copying.")模塊提供了一個易于使用的高級接口:
~~~
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'
~~~
### 10.2. 文件通配符
[glob](# "glob: Unix shell style pathname pattern expansion.")模塊提供了一個函數用于在目錄中以通配符搜索文件,并生成匹配的文件列表:
~~~
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
~~~
### 10.3. 命令行參數
常見的實用程序腳本通常需要處理命令行參數。這些參數以一個列表存儲在[sys](# "sys: Access system-specific parameters and functions.")模塊的*argv?*屬性中。例如下面的輸出結果來自于從命令行運行pythondemo.pyone?two?three:
~~~
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
~~~
[getopt](# "getopt: Portable parser for command line options; support both short and long option names.")模塊使用Unix [getopt()](# "getopt: Portable parser for command line options; support both short and long option names.")函數的約定處理*sys.argv*。[argparse](# "argparse: Command-line option and argument parsing library.")模塊提供更強大、 更靈活的命令行處理功能。
### 10.4. 錯誤輸出重定向和程序終止
[sys](# "sys: Access system-specific parameters and functions.")模塊還具有*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](# "re: Regular expression operations.")模塊為高級的字符串處理提供了正則表達式工具。對于復雜的匹配和操作,正則表達式提供了簡潔、優化的解決方案:
~~~
>>> 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](# "math: Mathematical functions (sin() etc.).")模塊為浮點運算提供了對底層 C 函數庫的訪問:
~~~
>>> import math
>>> math.cos(math.pi / 4.0)
0.70710678118654757
>>> math.log(1024, 2)
10.0
~~~
[random](# "random: Generate pseudo-random numbers with various common distributions.")模塊提供了進行隨機選擇的工具:
~~~
>>> 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
~~~
SciPy項目<[http://scipy.org](http://scipy.org)>有很多其它用于數值計算的模塊。
### 10.7. 互聯網訪問
有很多的模塊用于訪問互聯網和處理的互聯網協議。最簡單的兩個是從URL獲取數據的[urllib.request](# "urllib.request: Extensible library for opening URLs.") 和發送郵件的[smtplib](# "smtplib: SMTP protocol client (requires sockets)."):
~~~
>>> from urllib.request import urlopen
>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
... 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. 日期和時間
[datetime](# "datetime: Basic date and time types.")模塊提供了處理日期和時間的類,既有簡單的方法也有復雜的方法。支持日期和時間算法的同時,實現的重點放在更有效的處理和格式化輸出。該模塊還支持處理時區。
~~~
>>> # 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](# "zlib: Low-level interface to compression and decompression routines compatible with gzip."), [gzip](# "gzip: Interfaces for gzip compression and decompression using file objects."), [bz2](# "bz2: Interfaces for bzip2 compression and decompression."), [lzma](# "lzma: A Python wrapper for the liblzma compression library."), [zipfile](# "zipfile: Read and write ZIP-format archive files.") 和 [tarfile](# "tarfile: Read and write tar-format archive files.")。
~~~
>>> 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](# "timeit: Measure the execution time of small code snippets.")模塊快速證明了現代的方法更快一些:
~~~
>>> 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](# "timeit: Measure the execution time of small code snippets.")的精細的粒度相反,[profile](# "profile: Python source profiler.")和[pstats](# "pstats: Statistics object for use with the profiler.")模塊提供了針對更大代碼塊的時間度量工具。
### 10.11. 質量控制
開發高質量軟件的方法之一是為每一個函數開發測試代碼,并且在開發過程中經常進行測試。
[doctest](# "doctest: Test pieces of code within docstrings.")模塊提供一個工具,掃描模塊并根據程序中內嵌的文檔字符串執行測試。測試構造如同簡單的將它的輸出結果剪切并粘貼到文檔字符串中。通過用戶提供的例子,它發展了文檔,允許 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](# "unittest: Unit testing framework for Python.")模塊不像[doctest](# "doctest: Test pieces of code within docstrings.")模塊那樣容易,不過它可以在一個獨立的文件里提供一個更全面的測試集:
~~~
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 有"Batteries Included"的哲學。這最好是通過其較大的文件包的先進和強大功能。例如:
- [xmlrpc.client](# "xmlrpc.client: XML-RPC client access.")和[xmlrpc.server](# "xmlrpc.server: Basic XML-RPC server implementations.")模塊讓遠程過程調用變得輕而易舉。盡管模塊有這樣的名字,它不需要直接XML知識或處理 XML 。
- [email](# "email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents.")包是是一個處理電子郵件的庫,包括MIME和其它基于RFC 2822的郵件。與[smtplib](# "smtplib: SMTP protocol client (requires sockets).")和[poplib](# "poplib: POP3 protocol client (requires sockets).")用于實際發送和接收郵件,email包有一個完整的工具集用于構建或者解碼復雜郵件結構(包括附件),并實現互聯網編碼和頭協議。
- [xml.dom](# "xml.dom: Document Object Model API for Python.")和[xml.sax](# "xml.sax: Package containing SAX2 base classes and convenience functions.")的包為這種流行的數據交換格式提供了強大的支持。同樣,[csv](# "csv: Write and read tabular data to and from delimited files.")模塊支持以常見的數據庫格式直接讀取和寫入。這些模塊和包一起大大簡化了 Python 應用程序和其他工具之間的數據交換。
- 國際化支持模塊包括[gettext](# "gettext: Multilingual internationalization services.")、[locale](# "locale: Internationalization services.")和[codecs](# "codecs: Encode and decode data and streams.")包。
- Python 2 教程
- 1. 吊吊你的胃口
- 2. Python 解釋器
- 3. Python簡介
- 4. 控制流
- 5. 數據結構
- 6. 模塊
- 7. 輸入和輸出
- 8. 錯誤和異常
- 9. 類
- 10. 標準庫概覽
- 11. 標準庫概覽 — 第II部分
- 12.現在怎么辦?
- 13. 交互式輸入的編輯和歷史記錄
- 14. 浮點數運算:問題和局限
- Python 2 標準庫
- 1. 引言
- 2. 內建函數
- 3. 不太重要的內建函數
- 4. 內建的常量
- 5. 內建的類型
- 6. 內建的異常
- 7. String Services
- 8. Data Types
- 9. Numeric and Mathematical Modules
- 10. File and Directory Access
- 11. Data Persistence
- 13. File Formats
- 14. Cryptographic Services
- 15. Generic Operating System Services
- 16. Optional Operating System Services
- 17. Interprocess Communication and Networking
- 18. Internet Data Handling
- 20. Internet Protocols and Support
- 26. Debugging and Profiling
- 28. Python Runtime Services
- Python 2 語言參考
- 1. 簡介
- 2. 詞法分析
- 3. 數據模型
- 4. 執行模型
- 5. 表達式
- 6. 簡單語句
- 7. 復合語句
- 8. 頂層的組件
- 9. 完整的語法規范
- Python 3 教程
- 1. 引言
- 2. Python 解釋器
- 3. Python簡介
- 4. 控制流
- 5. 數據結構
- 6. 模塊
- 7. 輸入和輸出
- 8. 錯誤和異常
- 9. 類
- 10. 標準庫概覽
- 11. 標準庫概覽 — 第II部分
- 12.現在怎么辦?
- 13. 交互式輸入的編輯和歷史記錄
- 14. 浮點數運算:問題和局限