天天看点

python标准库-第一部分

  作者:奔跑的QQEE

python标准库-第一部分

一、操作系统接口

​os​

​模块为与操作系统交互提供了许多方法。例:

>>> import os
>>> os.getcwd()      # 返回当前工作目录
'C:\\Python26'
>>> os.chdir('/server/accesslogs')   # 改变当前工作目录
>>> os.system('mkdir today')   # R运行命令 mkdir
0      

使用​

​import os​

​​而不要使用​

​from os import *​

​​。这样在执行​

​open()​

​​方法时可以保证调用的是​

​os.open()​

​​方法而不是内置的​

​open()​

​​方法。这两种方法作用完全不同。​

​os.open(file,flags[,mode])​

​​是​

​打开文件并根据其提供的flags设置对应的flags,根据提供的mode设置对应的mode​

​​。​

​open(name[,mode[,buffering]])​

​​是​

​打开文件并返回文件对象​

​。

使用​

​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')    # 复制文件到新文件
>>> shutil.move('/build/executables', '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​

​​模块处理​

​sys.argv​

​​是通过使用unix系统的​

​getopt()​

​​方法。​

​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)
0.70710678118654757
>>> math.log(1024, 2)
10.0      

​random​

​模块提供了产生随机的方法。

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

>>> random.sample(xrange(100), 10)   # 不放回抽样
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]

>>> random.random()    # 随机浮点数
0.17970987693706186

>>> random.randrange(6)    # [0,6) 范围内产生随机整数
4      

七、网络接口

python中有很多访问互联网,处理网络协议的模块。有两个最简单的模块:​

​urllib2,smtplib​

​。

​urllib2​

​​用来检索指定URL代表的位置中的数据。​

​smtplib​

​用来发送邮件。例:

>>> import urllib2
>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     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('[email protected]', '[email protected]',
... """To: [email protected]
... From: [email protected]
...
... Beware the Ides of March.
... """)
>>> server.quit()      

八、日期时间

​datetime​

​模块提供了操作时间日期的类;有简单的操作方式,也有复杂的。用例如下:

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

>>> # 支持日期计算
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368      

九、数据压缩

python支持一般的压缩数据格式。不同模块实现不同压缩格式,如​

​zlib​

​​,​

​gzip​

​​ ,​

​bz2​

​​ ,​

​zipfile​

​​ ,​

​tarfile​

​。例:

>>> import zlib
>>> s = 'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979      

十、性能测定

python提供了用于测定性能的工具。例:

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

​模块。不过后两者用于测定大块代码段中关键部分代码的性能。

十一、质量控制

保证开发出高质量软件的方法之一是​

​测试​

​。这一方法要在开发过程中反复实行。

>>>def average(values):
...    """Computes the arithmetic mean of a list of numbers.
...
...    >>> print average([20, 30, 70])
...    40.0
...    """
...    return sum(values, 0.0) / len(values)

>>>import doctest
>>>doctest.testmod()   

TestResults(failed=0, attempted=1)  # 测试的结果      
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() 

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK