一、基礎部分
1、操作系統接口
os模塊提供了幾十個函數用於與操作系統交互,讓我們先看一段代碼:
>>> import os
>>> os.system('time 0:02')
0
>>> 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
0
說明:
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,如果有問題可以與那裏的站長直接交流。