python3測試工具開發快速入門教程9重要的標準庫-基礎篇

操作系統接口

os模塊提供了一些與操作系統交互的函數:


>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python36'
>>> 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這樣的大型模塊, 內置的open()和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')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'
  • 參考資料

[雪峯磁針石博客]python庫介紹-os.path: 平臺獨立的文件名操作

[雪峯磁針石博客]python庫介紹-pathlib: 文件系統對象

文件通配符

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(不推薦使用)模塊使用Unix getopt()函數處理 sys.argv。更多的複雜命令行處理參見argparse。

[雪峯磁針石博客]python庫介紹-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.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

statistics模塊計算數字數據的基本統計屬性(平均值,中位數,方差等):


>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095

[SciPy項目]https://scipy.org/about.html)有許多其他數值計算模塊。其中的numpy的數值計算和隨機數功能都很強悍。pandas則是數據分析的利器。scikit-learn則有強大的統計功能。

  • 參考資料:

[雪峯磁針石博客]scikit-learn_cookbook1: 高性能機器學習-NumPy

互聯網訪問

有幾個模塊用於訪問互聯網以及處理網絡通信協議。其中最簡單的:urllib.request從URL獲取信息;發送電子郵件的smtplib。


>>> from urllib.request import urlopen
>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
...     for line in response:
...         line = line.decode('utf-8')  # Decoding the binary data to text.
...         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('[email protected]', '[email protected]',
... """To: [email protected]
... From: [email protected]
...
... Beware the Ides of March.
... """)
>>> server.quit()

(注意第二個例子需要在localhost運行郵件服務器。)

日期和時間

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

性能度量

例如元組封裝和解包來交換元素比使用傳統的方法更快。


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

profile和、pstats提供了針對更大代碼塊的時間度量工具。

質量控制

一種開發高質量軟件的方法是爲每個函數開發測試代碼,並且在開發過程中經常進行測試。

doctest根據程序中內嵌的文檔字符串執行測試。測試構造如同簡單的將它的輸出結果剪切並粘貼到文檔字符串中,通過式通過實例改善了文檔:


def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / 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

外部庫pytest提供了極其強悍的測試功能,很多測試平臺就是基於pytest構建的。nose也是一個不錯的選擇。

  • 參考資料

[雪峯磁針石博客]python外部測試框架
[雪峯磁針石博客]自動化測試框架pytest教程

參考資料

更多庫簡介

  • xmlrpc.client和xmlrpc.server模塊讓遠程過程調用變得輕而易舉。用戶無需處理XML。

  • email 包是管理郵件信息的庫,包括MIME和其它基於RFC2822的信息文檔。不同於實際發送和接收信息的 smtplib 和 poplib 模塊,email包含構造或解析複雜消息結構(包括附件)及實現互聯網編碼和頭協議的完整工具集。

  • json包爲解析json這種流行的數據交換格式提供了強大的支持。 csv模塊支持直接讀寫逗號分隔值格式文件。 XML處理由xml.etree.ElementTree,xml.dom和xml.sax包支持。

  • sqlite3模塊提供了一個持久數據庫,可以使用與標準的SQL略有差異的語法來更新和訪問。

  • 國際化由 gettext, locale 和 codecs 包支持。

  • [雪峯磁針石博客]python庫介紹-collections:高性能容器數據類型, 提供有序字典、命名元組和雙端隊列等數據類型。

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