python17:基础库概述

这篇博客概述了Python的基础库,包括操作系统接口、文件通配符、命令行参数、错误处理、字符串模式匹配、数学运算、网络、日期时间、数据压缩和效率测试等方面,还提到了质量控制,如doctest模块用于测试函数。
摘要由CSDN通过智能技术生成

这里对python的基础库做一个简要概述,包括每个模块的基本功能和常用操作。更详细的信息请参考Python库参考。

操作系统接口

操作系统接口对应os模块,用于与操作系统交互:

>>> import os
>>> os.getcwd()      # 返回当前的工作目录
'C:\\Python34'
>>> os.chdir('/server/accesslogs')   # 改变当前工作目录
>>> os.system('mkdir today')   # 运行系统命令mkdir
0
注意使用import os导入os模块,不要使用from os import *,防止os.open()和内建函数open()冲突。
内建函数dir()和help()可以帮助使用os这样的大模块:

>>> import os
>>> dir(os)
<返回所有模块方法的列表>
>>> help(os)
<返回模块的手册,该手册来自模块的docstrings>
对于日常文件和文件夹管理任务,shutil模块提供了更易用的更高层次的接口。

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

文件通配符

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模块提供。

错误输出重定向和程序终止

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

字符串模式匹配

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'
当今需要简单的功能时,string的方法是更好的,因为他们更加易于理解和阅读:

>>> '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
SciPy项目<http://scipy.org>为数字计算提供了多个模块。

网络

有多个模块用于连接internet和处理internet协议。其中最简单的两个是urllib.request(用于从URL获取数据)和smtplib(发送邮件):

>>> from urllib.request import urlopen
>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
        line = line.decode('utf-8')  # 解码二进制数据到文本
        if 'EST' in line or 'EDT' in line: 
            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。

日期和时间

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

效率测试

一些用户对于效率问题非常关注,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模块提供了为大块代码做效率测试的工具。

质量控制

开发高质量软件的一个方法是为每个函数写测试,并在开发的过程中频繁的执行这些测试。
doctest模块提供了工具,用于扫描一个模块并验证嵌入在程序的docstring中的测试。测试是尽可能简单的语句,并包含它的结果。

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个

红包金额最低5元

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

抵扣说明:

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

余额充值