第十章 标准库简介——python导引编译之十一

第十章 标准库简介——python导引编译之十一

标题10.标准库简介Brief Tour of the Standard Library

标题10.1.作业系统介面 Operating System Interface

os模块(即操作系统界面)提供了许多与操作系统交互的功能:

>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python39'
>>> os.chdir('/server/accesslogs')   # Change current working directory
>>> os.system('mkdir today')   # Run the command mkdir in the system shell
0

确信使用 os样式而不是from os import *样式。这将防止os.open()遮盖内置的open()函数,该函数的运行方式大不相同。
内置的dir()和help()函数可用作交互式辅助工具,用于处理诸如os之类的大型模块:

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

标题10.2.通配符 File Wildcards

glob模块提供了通过目录通配符搜索创建文件列表的功能:

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

标题10.3.命令行参数Command Line Arguments

通用实用程序脚本通常需要处理命令行参数。这些参数作为列表存储在sys模块的argv属性中。
例如,以下输出是在命令行运行python demo.py一二三的结果:

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

argparse模块提供了一种更复杂的机制来处理命令行参数。以下脚本提取一个或多个文件名以及要显示的可选行数:

import argparse

parser = argparse.ArgumentParser(prog = 'top',
    description = 'Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)

当python top.py --lines = 5 alpha.txt beta.txt在命令行中运行时,脚本会将args.lines设置为5,并将args.filenames设置为[‘alpha.txt’,‘beta.txt’]。

标题10.4.错误输出重定向和程序终止Error Output Redirection and Program Termination

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.字符串模式匹配String Pattern Matching

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.数学Mathematics

math模块可访问用于浮点数学运算的基础C库函数:

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

随机模块提供了用于进行随机选择的工具:

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

统计模块计算数字数据的基本统计属性(均值,中位数,方差等):

>>> 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还有许多其他用于数值计算的模块。

标题10.7.互联网访问Internet Access

有许多用于访问Internet和处理Internet协议的模块。其中最简单的两个是用于从URL检索数据的urllib.request和用于发送邮件的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('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()

(请注意其中的第二个例子需要在当地主机上运行的邮箱服务器。)

标题10.8.日期和时间Dates and Times

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.数据压缩Data Compression

常见的数据归档和压缩格式,包括: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.绩效评估Performance Measurement

有些python用户对了解针对同一问题的不同方法的相对性能产生了浓厚的兴趣。 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.质量控制Quality Control

开发高质量软件的一种方法是在开发每个功能时编写测试,并在开发过程中频繁运行这些测试。
doctest模块提供了一种工具,用于扫描模块并验证嵌入在程序docstring中的测试。
测试构造就像将一个典型的调用及其结果粘贴到文档字符串中一样简单。这通过为用户提供示例来改善文档,并允许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

标题10.12.包括电池Batteries Included

python有一种“包括电池”的哲学。这最好被看作是,通过其更大封装中的复杂和强大功能实现目标。
例如:

xmlrpc.client和xmlrpc.server模块使实现远程过程调用几乎变成了平凡又平凡的任务。尽管有模块名称,但不需要直接了解或处理XML。

电子邮件包是用于管理电子邮件的库,包括MIME和其他基于RFC 2822的消息文档。与实际发送和接收消息的smtplib和poplib不同,电子邮件包具有用于构建或解码复杂的消息结构(包括附件)以及实现Internet编码和标头协议的完整工具集。

json包为解析这种流行的数据交换格式提供了强大的支持。 csv模块支持直接读取和写入逗号分隔值格式的文件,通常由数据库和电子表格支持。 xml.etree.ElementTree,xml.dom和xml.sax包支持XML处理。这些模块和软件包一起极大地简化了Python应用程序和其他工具之间的数据交换。

sqlite3模块是SQLite数据库库的包装,提供了一个永久数据库,可以使用稍微有点不标准的SQL语法进行更新和访问。

许多模块都支持国际化,包括gettext,locale和codecs包。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值