Python風格總結:Python3 標準庫概覽

操作系統接口

os模塊提供了不少與操作系統相關聯的函數。

>>> import os
>>> os.getcwd()      # 返回當前的工作目錄
'C:\\Python34'
>>> os.chdir('/server/accesslogs')   # 修改當前的工作目錄
>>> os.system('mkdir today')   # 執行系統命令 mkdir 
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>

針對日常的文件和目錄管理任務,:mod:shutil 模塊提供了一個易於使用的高級接口:

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')

數學

math模塊爲浮點運算提供了對底層C函數庫的訪問:

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

random提供了生成隨機數的工具。

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

日期和時間

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

數據壓縮

以下模塊直接支持通用的數據打包和壓縮格式:zlib,gzip,bz2,zipfile,以及 tarfile。

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

性能度量

有些用戶對了解解決同一問題的不同方法之間的性能差異很感興趣。Python 提供了一個度量工具,爲這些問題提供了直接答案。

例如,使用元組封裝和拆封來交換元素看起來要比使用傳統的方法要誘人的多,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 的細粒度,:mod:profile 和 pstats 模塊提供了針對更大代碼塊的時間度量工具。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章