10. Python 標準函式庫概覽
*************************


10.1. 作業系統介面
==================

"os" 模組提供了數十個與作業系統溝通的函式：

   >>> import os
   >>> os.getcwd()      # Return the current working directory
   'C:\\Python26'
   >>> 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()"。

在使用 "os" 諸如此類大型模組時搭配內建函式 "dir()" 和 "help()" 是非常
有用的:

   >>> 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')
   >>> shutil.move('/build/executables', 'installdir')


10.2. 檔案之萬用字元
====================

The "glob" module provides a function for making file lists from
directory wildcard searches:

   >>> import glob
   >>> glob.glob('*.py')
   ['primes.py', 'random.py', 'quote.py']


10.3. 命令列引數
================

通用工具腳本常需要處理命令列引數。這些引數會以串列形式存放在 "sys" 模
組的 *argv* 此變數中。例如在命令列執行 "python demo.py one two three"
會有以下輸出結果:

   >>> import sys
   >>> print sys.argv
   ['demo.py', 'one', 'two', 'three']

"getopt" 模組使用Unix "getopt()" 函式來處理 *sys.argv*。更強大且具有彈
性的命令列處理可由 "argparse" 模組提供。


10.4. 錯誤輸出重新導向與程式終止
================================

"sys" 模組也有 *stdin*，*stdout*，和 *stderr* 等變數。即使當 *stdout*
被重新導向時，後者 *stderr* 可輸出發送警告和錯誤訊息。

   >>> 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" 模組提供正規表示式 (regular expression) 做進階的字串處理。當要處
理複雜的比對以及操作時，正規表示式是簡潔且經過最佳化的解決方案。

   >>> 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)
   0.70710678118654757
   >>> math.log(1024, 2)
   10.0

"random" 模組提供了隨機選擇的工具。

   >>> import random
   >>> random.choice(['apple', 'pear', 'banana'])
   'apple'
   >>> random.sample(xrange(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


10.7. 網路存取
==============

There are a number of modules for accessing the internet and
processing internet protocols. Two of the simplest are "urllib2" for
retrieving data from URLs and "smtplib" for sending mail:

   >>> import urllib2
   >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
   ...     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" 模組中有許多類別供以操作日期以及時間，從簡單從複雜都有。模
組支援日期與時間的運算，而實作的重點是有效率的成員擷取以達到輸出格式化
以及操作。模組也提供支援時區換算的類別。

   >>> # 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. 資料壓縮
==============

Common data archiving and compression formats are directly supported
by modules including: "zlib", "gzip", "bz2", "zipfile" and "tarfile".

   >>> import zlib
   >>> s = 'witch which has which witches wrist watch'
   >>> len(s)
   41
   >>> t = zlib.compress(s)
   >>> len(t)
   37
   >>> zlib.decompress(t)
   'witch which has which witches wrist watch'
   >>> zlib.crc32(s)
   226805979


10.10. 效能量測
===============

有一些 Python 使用者很想了解同個問題的不同實作方法的效能差異。 Python
提供評估了效能差異的工具。

舉例來說， 有人可能會試著用 tuple 的打包機制來交換引數代替傳統的方式。
"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" 模組
則提供了一些在大型的程式碼識別關鍵臨界區間（Critical Section）的工具。


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, 0.0) / 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設計哲學。 它的好處是可以透過這些套件
使用複雜與強大的功能。 例如:

* The "xmlrpclib" and "SimpleXMLRPCServer" modules make implementing
  remote procedure calls into an almost trivial task.  Despite the
  modules names, no direct knowledge or handling of XML is needed.

* The "email" package is a library for managing email messages,
  including MIME and other RFC 2822-based message documents. Unlike
  "smtplib" and "poplib" which actually send and receive messages, the
  email package has a complete toolset for building or decoding
  complex message structures (including attachments) and for
  implementing internet encoding and header protocols.

* The "xml.dom" and "xml.sax" packages provide robust support for
  parsing this popular data interchange format. Likewise, the "csv"
  module supports direct reads and writes in a common database format.
  Together, these modules and packages greatly simplify data
  interchange between Python applications and other tools.

* 有數種支援國際化模組 "gettext"，"locale"，和 "codecs" 等套件。
