作者:奔跑的QQEE
python标準庫-第一部分
一、作業系統接口
os
子產品為與作業系統互動提供了許多方法。例:
>>> import os
>>> os.getcwd() # 傳回目前工作目錄
'C:\\Python26'
>>> os.chdir('/server/accesslogs') # 改變目前工作目錄
>>> os.system('mkdir today') # R運作指令 mkdir
0
使用
import os
而不要使用
from os import *
。這樣在執行
open()
方法時可以保證調用的是
os.open()
方法而不是内置的
open()
方法。這兩種方法作用完全不同。
os.open(file,flags[,mode])
是
打開檔案并根據其提供的flags設定對應的flags,根據提供的mode設定對應的mode
。
open(name[,mode[,buffering]])
是
打開檔案并傳回檔案對象
。
使用
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') # 移動檔案到新目錄
二、檔案通配符
glob
子產品提供了使用通配符查找檔案清單的方法。例:
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
三、指令行參數
經常需要處理指令行參數。這些參數以清單的形式存儲在
sys
子產品的
argv
屬性中。下例結果是在指令行中執行完
python demo.py one two three
後得到的:
>>> import sys
>>> print sys.argv
['demo.py', 'one', 'two', 'three']
getopt
子產品處理
sys.argv
是通過使用unix系統的
getopt()
方法。
argparse
子產品提供了更為強大靈活的指令行處理方法。
四、錯誤結果輸出與終端操作
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()
。
五、字元串樣式比對
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'
六、數學處理
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) # 不放回抽樣
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random() # 随機浮點數
0.17970987693706186
>>> random.randrange(6) # [0,6) 範圍内産生随機整數
4
七、網絡接口
python中有很多通路網際網路,處理網絡協定的子產品。有兩個最簡單的子產品:
urllib2,smtplib
。
urllib2
用來檢索指定URL代表的位置中的資料。
smtplib
用來發送郵件。例:
>>> import urllib2
>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
... if 'EST' in line or 'EDT' in line: # 查找東部時間
... print line
<BR>Nov. 25, 09:43:32 PM EST
>>> import smtplib # 此例的正常運作需要運作在本地的郵件伺服器
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('[email protected]', '[email protected]',
... """To: [email protected]
... From: [email protected]
...
... Beware the Ides of March.
... """)
>>> server.quit()
八、日期時間
datetime
子產品提供了操作時間日期的類;有簡單的操作方式,也有複雜的。用例如下:
>>> 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.'
>>> # 支援日期計算
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
九、資料壓縮
python支援一般的壓縮資料格式。不同子產品實作不同壓縮格式,如
zlib
,
gzip
,
bz2
,
zipfile
,
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
十、性能測定
python提供了用于測定性能的工具。例:
>>> 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
子產品。不過後兩者用于測定大塊代碼段中關鍵部分代碼的性能。
十一、品質控制
保證開發出高品質軟體的方法之一是
測試
。這一方法要在開發過程中反複實行。
>>>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()
TestResults(failed=0, attempted=1) # 測試的結果
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()
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK