天天看點

pytohn标準庫概要 .一、基礎部分二、專業部分

一、基礎部分

1、作業系統接口

os子產品提供了幾十個函數用于與作業系統互動,讓我們先看一段代碼:

>>> import os

>>> os.system('time 0:02')

>>> os.getcwd()

'C://Python24'

>>> os.chdir('/server/accesslogs')

說明:

os.system(command):執行一個指令(command)

os.getcwd():得到目前的工作目錄

os.chdir():改變目前目錄到指定目錄

注意:這裡不可以用from os import *,因為os.open()是和内建的open()不同的。

在你使用較大的子產品的時候,Python的内建函數dir()和help()可以為你提供很大的幫助,讓你對該子產品多一些了解。

例如:

>>> import os
>>> dir(os)
['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 
'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 
'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 
'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 
'R_OK','TMP_MAX', 'UserDict', 'W_OK', 'X_OK', '_Environ', 
'__all__', '__builtins__', '__doc__', '__file__', '__name__', 
'_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', 
'_make_stat_result', '_make_statvfs_result', 
'_pickle_stat_result','_pickle_statvfs_result', 'abort', 'access', 
'altsep', 'chdir', 'chmod', 'close', 'curdir', 
'defpath','devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 
'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 
'execvpe', 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 
'getcwdu', 'getenv', 'getpid', 'isatty', 'linesep', 'listdir', 
'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 
'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 
'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 
'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 
'startfile', 'stat', 'stat_float_times', 'stat_result', 
'statvfs_result', 'strerror', 'sys', 'system', 'tempnam', 'times', 
'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom',
 'utime', 'waitpid', 'walk', 'write']
 >>> help(os) Help on module os:  NAME     os - OS routines for Mac, DOS, NT, or Posix depending on what 
system we're on.
  FILE     c:/python24/lib/os.py  DESCRIPTION     This exports:       - all functions from posix, nt, os2, mac, or ce, e.g. unlink, 
stat, etc.
      - os.path is one of the modules posixpath, ntpath, or macpath
 ...    ...       

說明:

dir(os):傳回該子產品所有屬性的一個清單

help(os):傳回該子產品的使用手冊

對于檔案和目錄的管理,shutil子產品提供了一個進階的接口,很好用。

例如:

>>> import shutil

>>> shutil.copyfile('data.db', 'archive.db')

>>> shutil.move('/build/executables', 'installdir')

說明:

shutil.copyfile(src, dst):将src代表的檔案複制資料給dst代表的檔案

shutil.move(src, dst):遞歸的将src代表的檔案或目錄移動到dst代表的位置處

2、檔案通配符

glob子產品提供了一個glob函數,用來支援目前目錄下的通配符搜尋。

例如:

>>> import glob

>>> glob.glob('*.py')

['primes.py', 'random.py', 'quote.py']

說明:

glob.glob('*.py'):傳回目前目錄下所有字尾為py的檔案。

3、指令行參數

通常情況下我們的腳本都需要指令行參數。這些參數都存儲在sys.argv中。 getopt子產品使用unix的getopt函數的慣例來處理sys.argv。optparse子產品提供了更強大,靈活的功能來處理sys.argv。

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()。

5、字元串模式比對

re子產品為字元串的進階處理提供了正規表達式工具。對于複雜的比對和處理,正規表達式提供了簡潔、優化的方法。

6、數學處理

math子產品提供了處理浮點數的方法。

示例如下:

>>> 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)

[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]

>>> random.random()

0.17970987693706186

>>> random.randrange(6)

4

7、internet通路

Python提供了大量的用于通路internet和處理internet協定的子產品。其中最簡單的兩個是urllib2和smtplib。urllib2用于從url得到資料,smtplib用于發送郵件。

8、日期和時間

datetime子產品為用簡單和複雜方法去處理日期和時間提供了類。

示例如下:

>>> from datetime import date

>>> now=date.today()

>>> now

datetime.date(2006, 7, 1)

>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")

'07-01-06. 01 Jul 2006 is a Saturday on the 01 day of July.'

>>> birthday = date(2006, 7, 1)

>>> age = now - birthday

>>> age.days

說明:

date.today():得到目前日期的date對象,如datetime.date(2006, 7, 1)

strftime:将日期時間字元串格式化

date(2006, 7, 1):建一指定日期的日期象

now - birthday:日期對象可以進行算術運算

9、資料壓縮

支援資料壓縮的子產品有:zlib、gzip、bz2、zipfile和tarfile。

下面是一個zlib的例子:

>>> 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

說明:

compress():壓縮字元串

decompress():解壓縮指定的已被壓縮的字元串

crc32():計算給定字元串的CRC-32校驗和

10、性能測定

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

說明:

Timer('t=a; a=b; b=t', 'a=1; b=2').timeit():測量語句的執行時間

子產品profile和pstats則用于對大塊代碼的測定。

11、品質控制

開發高品質的軟體方法是為每一個所開發的函數寫一個測試,并在開發過程中頻繁的測試它們。

doctest子產品為掃描一個子產品和确認内嵌在程式文檔字元串中的測試提供了一種手段。這個測試部分我們可以将執行的指令和結果寫到函數的文檔字元串中。通過這個包含測試部分的文檔字元串,我們可以驗證我們的函數能否得到想要的結果。

示例如下:

#!/usr/bin/python
#filename: qc.py


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)

def _test():#以下兩句必須包含在要測試的子產品中
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()
      

說明:>>> print average([20, 30, 70])#要執行的指令

40.0 #預期應有的結果。這就形成了一個測試部分

運作輸出如下:

C:/WINDOWS>python f:/pythontools/test/qc.py -v
Trying:
    print average([20, 30, 70])
Expecting:
    40.0
ok
2 items had no tests:
    __main__
    __main__._test
1 items passed all tests:
   1 tests in __main__.average
1 tests in 3 items.
1 passed and 0 failed.
Test passed.
      

說明:

C:/WINDOWS>python f:/pythontools/test/qc.py -v:沒有-v,如果通過測試,則不作任何顯示。

Test passed.:說明測試通過。

unittest子產品沒有doctest子產品那麼容易使用,但是它提供了在一個單獨檔案中進行一套全面測試的手段。

示例如下:

import unittest
from qc import *
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)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

unittest.main() # Calling from the command line invokes all tests
      

運作輸出如下:

C:/WINDOWS>python f:/pythontools/test/ut.py

.

--------------------------------------------

Ran 1 test in 0.000s

OK

12、強大能力

Python的大量成熟而完善的包展現了它強大的能力。

舉例說明如下:

a、xmlrpclib和SimpleXMLRPCServer子產品實作了遠端建立瑣細任務。

b 、email包是一個用來管理email資訊的庫,包括管理MIME和别的RFC 2822-based資訊文檔。不像smtplib和poplib,email包有一整套工具用于建立或解碼複雜的資訊結構和實作internet編碼和報頭協定。

c、xml.dom和xml.sax包為分析流行的資料交換協定提供了足夠的支援。同樣,csv子產品支援用一般的資料庫格式直接讀寫。這幾個子產品在python應用程式和别的工具之間提供了非常簡單的資料交換。

d、大量的子產品提供了對國際化的支援,包括gettext,locale和codec包。

二、專業部分

1、格式化輸出

repr子產品提供了一個repr()的譯本用于大的嵌套的簡短顯示。

示例如下:

>>> import repr

>>> repr.repr(set('supercalifragilisticexpialidocious'))

"set(['a', 'c', 'd', 'e', 'f', 'g', ...])"

pprint子產品提供了為解釋器可讀的更成熟的對列印内建和使用者自定義對象的控制。當列印輸出超過一行時,靈活的列印程式會添加換行符和縮進以清楚的顯示資料的結構。

示例如下:

>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
     ...     'yellow'], 'blue']]]     ... >>> pprint.pprint(t, width=30) [[[['black', 'cyan'],    'white',    ['green', 'red']],   [['magenta', 'yellow'],    'blue']]]        

textwrap子產品格式化文本的段落以适合給定螢幕的寬度,示例如下:

>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it 
returns
... a list of strings instead of one big string with newlines to
 separate
... the wrapped lines."""
...
>>> print textwrap.fill(doc, width=40)
    The wrap() method is just like fill()
    except that it returns a list of strings
    instead of one big string with newlines
    to separate the wrapped lines.
      

locale子產品用于通路具體資料格式的資料庫,示例如下:

>>> import locale

>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')

'English_United States.1252'

>>> conv = locale.localeconv()

>>> x = 1234567.8

>>> locale.format("%d", x, grouping=True)

'1,234,567'

>>> locale.format("%s%.*f", (conv['currency_symbol'],

... conv['frac_digits'], x), grouping=True)

'$1,234,567.80'

2、模闆

string模闆包括了一個通用的Template類, 這個類為終端使用者的編輯提供了一個簡單的文法。

3、處理二進制

struct子產品提供了pack()和unpack()函數用于處理可變長的二進制。

4、多線程

threading子產品提供了相關的功能。

5、日志

logging提供了一個完整而靈活的日志系統。

6、引用

weakref提供了不建立引用而跟蹤對象的工具。它使得記憶體資源不會造成不合理的浪費。

7、用于清單的工具

用于清單的工具很多,但有時候我們需要根據它們的性能作出選擇。這兒有幾個子產品,它們的性能特點有所差別,這裡隻列出它們的名稱:array,collections,bisect, heapq 。

8、浮點小數算法

decimal子產品提供了處理浮點小數算法的手段。

本系列的文章來源是http://www.pythontik.com/html,如果有問題可以與那裡的站長直接交流。