1. 程式人生 > >《Python3.6官方文件》– 第十章

《Python3.6官方文件》– 第十章

作業系統介面

os 模組提供一系列與作業系統進行互動的函式。

import os
os.getcwd()      # 返回當前工作目錄
os.chdir('/server/accesslogs')   #  修改當前工作目錄
os.system('mkdir today')   # 在系統shell中執行mkdir命令

確保使用 import os 而不是 from os import * .它將導致覆蓋隱式內建函式,它們是完全不同的.

諸如os等大模組工作時,一些內建函式dir() , 的互動式幫助是很有用的.

import os
dir(os)
help(os)

針對日常的檔案、目錄的管理任務,模組提供了易用的高階介面.

import shutil

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

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

檔案萬用字元

glob 模組提供了通過萬用字元列出檔案列表的功能.

import glob

glob.glob('*.py')

命令列引數

常見的實用指令碼通常需要處理命令列引數,這些引數以list的形式儲存在sys 模組的argv屬性中.

使用下面的程式碼執行python demo.py one two three`

import sys

print(sys.argv)
結果為 ['demo.py', 'one', 'two', 'three']

模組約定使用Unix的 getopt() 函式處理sys.argv,argparse 模組提供了更強大易拓展的命令列處理流程.

錯誤輸出重定向&程式終止

[sys]模組擁有 stdin,stdout和stderr屬性,stderr是很有用的,即使在stdout被重定向後,由它發出警告和錯誤資訊也都是可見的.

sys.stderr.write('Warning, log file not found starting a new one\n')

sys.exit() 是停掉指令碼最直接的方式

字元模式匹配

re 模組為高階的字元處理提供了正則表示式工具. 針對複雜的匹配和處理,正則表示式提供了簡明的解決方式.

import re

re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')

re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')

當僅僅需要一些簡單的功能時,string 方法是更合適的選擇,它的可讀性更高,更易進行debug.

'tea for too'.replace('too', 'two')

數學運算

math 模組為浮點運算提供了基於C library 函式的入口

import math

math.cos(math.pi / 4)



math.log(1024, 2)

random 模組提供了進行隨機選擇的工具.
import random

random.choice(['apple', 'pear', 'banana'])

random.sample(range(100), 10)   # sampling without replacement

random.random()    # random float

random.randrange(6)    # random integer chosen from range(6)

statistic模組計算數值的基本統計屬性(均值,中位數,方差等)

import statistics

data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]

statistics.mean(data)

statistics.median(data)

statistics.variance(data)

SciPy 工程有很多進行數值運算的模組

接入網際網路

有很多模組可用於接入網際網路並處理網際網路協議,這裡列舉兩個最簡單的:

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)
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執行一個郵件服務)

日期和時間

提供了可以通過簡單或複雜方式處理日期和時間的類,在提供日期時間運算的同時,側重於高效的為格式化輸出和處理進行成員匯出,也支援時區相關的物件.

# dates are easily constructed and formatted

from datetime import date

now = date.today()

now

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


# dates support calendar arithmetic

birthday = date(1964, 7, 31)

age = now - birthday

age.days

資料壓縮

(zlib,
gzip,
bz2,
lzma,
,
)等模組支援常見的檔案歸檔和壓縮格式

import zlib

s = b'witch which has which witches wrist watch'

len(s)

t = zlib.compress(s)

len(t)

zlib.decompress(t)

zlib.crc32(s)

效能衡量

一些Python使用者對了解解決同一問題的不同解決方式的實際效能有著很深的興趣,Python為直接地這些問題提供了測量工具。

例如:直接使用tuple裝包和開包特性替代傳統的引數交換方式是很有吸引力的, 快速示範了一定程度上的效能優勢。

from timeit import Timer Timer(‘t=a; a=b; b=t’, ‘a=1; b=2’).timeit() Timer(‘a,b = b,a’, ‘a=1; b=2’).timeit()

質量控制

開發高質量的軟體的一種方法是在開發軟體的過程中為每個function編寫測試,並在開發過程中頻繁的執行這些測試.

提供可以掃描並驗證通過程式文件注入的測試.測試的構建和剪下貼上一個呼叫和結果到文件中一樣簡單,它通過提供給使用者一個例子和一個文件測試來確保程式碼和文件的一致性來改善文件。

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

沒有 那麼簡潔易用,但是它允許在一個單獨的測試檔案中維護更為複雜的測試集

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

內建電池

Python有一個’內建電池’理念,它能很好地通過一些成熟並且健壯的package表現出來。例如:

  • 和 將遠端程式呼叫實現成了簡單的任務,儘管叫這個名字,但不需直接瞭解或處理xml。
  • emailpackage是一個負責管理郵件訊息的庫,包含MIME和其他RFC2822-base訊息檔案,不像smtplibpiplib一樣真正的進行訊息收發,email package有一個複雜工具集來構建或解碼複雜訊息結構(包括附件)及實現網路編碼和報頭協議
  • json為解析這種流行的資料交換格式提供了強大的支援,csv支援以逗號進行分隔值的形式進行檔案的讀寫,通常支援資料庫和電子表格,xml.etree.ElementTree, xml.dom 和 xml.sax對xml程式提供支援,這些package極大地簡化了Python和其他工具間的資料交換。
  • sqlite3是對SQLite資料庫庫的包裝,提供了一個永續性資料庫,可以使用稍微不標準SQL語法對資料庫進行更新和訪問。
  • 國際化由gettextlocalcodecs等package提供支援