日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python学习笔记: Python 标准库概览

發布時間:2025/3/15 python 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python学习笔记: Python 标准库概览 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文來自:入門指南
開胃菜參考:開胃菜
使用Python解釋器:使用Python解釋器
本文對Python的簡介:Python 簡介
Python流程介紹:深入Python 流程
Python數據結構:Python 數據結構
Python:模塊:Python 模塊
Python:輸入和輸出Python 輸入和輸出
Python:錯誤和異常Python 錯誤和異常
Python:類Python:類

目錄:

  • 目錄:
  • 10. Python 標準庫概覽
    • 10.1. 操作系統接口
    • 10.2. 文件通配符
    • 10.3. 命令行參數
    • 10.4. 錯誤輸出重定向和程序終止
    • 10.5. 字符串正則匹配
    • 10.6. 數學
    • 10.7. 互聯網訪問
    • 10.8. 日期和時間
    • 10.9. 數據壓縮
    • 10.10. 性能度量
    • 10.11. 質量控制
    • 10.12. “瑞士軍刀”

10. Python 標準庫概覽

10.1. 操作系統接口

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

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

10.2. 文件通配符

glob 模塊提供了一個函數用于從目錄通配符搜索中生成文件列表:

>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py']

10.3. 命令行參數

通用工具腳本經常調用命令行參數。這些命令行參數以鏈表形式存儲于 sys 模塊的 argv 變量。例如在命令行中執行 python demo.py one two three 后可以得到以下輸出結果:

>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three']

getopt 模塊使用 Unix getopt() 函數處理 sys.argv。更多的復雜命令行處理由 argparse 模塊提供。

10.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()。

10.5. 字符串正則匹配

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'

10.6. 數學

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(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) 4SciPy <http://scipy.org> 項目提供了許多數值計算的模塊。

10.7. 互聯網訪問

有幾個模塊用于訪問互聯網以及處理網絡通信協議。其中最簡單的兩個是用于處理從 urls 接收的數據的 urllib.request 以及用于發送電子郵件的 smtplib:

>>> from urllib.request import urlopen >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... 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('soothsayer@example.org', 'jcaesar@example.org', ... """To: jcaesar@example.org ... From: soothsayer@example.org ... ... Beware the Ides of March. ... """) >>> server.quit()

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

10.8. 日期和時間

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

10.9. 數據壓縮

以下模塊直接支持通用的數據打包和壓縮格式: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

10.10. 性能度量

有些用戶對了解解決同一問題的不同方法之間的性能差異很感興趣。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 的細粒度,profile 和 pstats 模塊提供了針對更大代碼塊的時間度量工具。

10.11. 質量控制

開發高質量軟件的方法之一是為每一個函數開發測試代碼,并且在開發過程中經常進行測試。
doctest 模塊提供了一個工具,掃描模塊并根據程序中內嵌的文檔字符串執行測試。測試構造如同簡單的將它的輸出結果剪切并粘貼到文檔字符串中。通過用戶提供的例子,它發展了文檔,允許 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 unittestclass 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

10.12. “瑞士軍刀”

Python 展現了“瑞士軍刀”的哲學。這可以通過它更大的包的高級和健壯的功能來得到最好的展現。列如:

xmlrpc.client 和 xmlrpc.server 模塊讓遠程過程調用變得輕而易舉。盡管模塊有這樣的名字,用戶無需擁有 XML 的知識或處理 XML。email 包是一個管理郵件信息的庫,包括MIME和其它基于 RFC2822 的信息文檔。email 包包含一個構造或解析復雜消息結構(包括附件)及實現互聯網編碼和頭協議的完整工具集。xml.dom 和 xml.sax 包為流行的信息交換格式提供了強大的支持。同樣, csv 模塊支持在通用數據庫格式中直接讀寫。綜合起來,這些模塊和包大大簡化了 Python 應用程序和其它工具之間的數據交換。國際化由 gettext, locale 和 codecs 包支持。

總結

以上是生活随笔為你收集整理的Python学习笔记: Python 标准库概览的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。