一、基础部分
1、操作系统接口
os模块提供了几十个函数用于与操作系统交互,让我们先看一段代码:
>>> import os
>>> os.system('time 0:02')
0
>>> os.getcwd()
'C://Python24'
>>> os.chdir('/server/accesslogs')
说明:
os.system(command):执行一个命令(command)
os.getcwd():得到当前的工作目录
os.chdir():改变当前目录到指定目录
注意:这里不可以用from os import *,因为os.open()是和内建的open()不同的。
在你使用较大的模块的时候,Python的内建函数dir()和help()可以为你提供很大的帮助,让你对该模块多一些了解。
例如:
>>> import os
>>> dir(os)
['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT',
'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL',
'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY',
'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT',
'R_OK','TMP_MAX', 'UserDict', 'W_OK', 'X_OK', '_Environ',
'__all__', '__builtins__', '__doc__', '__file__', '__name__',
'_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list',
'_make_stat_result', '_make_statvfs_result',
'_pickle_stat_result','_pickle_statvfs_result', 'abort', 'access',
'altsep', 'chdir', 'chmod', 'close', 'curdir',
'defpath','devnull', 'dup', 'dup2', 'environ', 'error', 'execl',
'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp',
'execvpe', 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd',
'getcwdu', 'getenv', 'getpid', 'isatty', 'linesep', 'listdir',
'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir',
'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4',
'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames',
'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve',
'startfile', 'stat', 'stat_float_times', 'stat_result',
'statvfs_result', 'strerror', 'sys', 'system', 'tempnam', 'times',
'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom',
'utime', 'waitpid', 'walk', 'write']
>>> help(os) Help on module os: NAME os - OS routines for Mac, DOS, NT, or Posix depending on what
system we're on.
FILE c:/python24/lib/os.py DESCRIPTION This exports: - all functions from posix, nt, os2, mac, or ce, e.g. unlink,
stat, etc.
- os.path is one of the modules posixpath, ntpath, or macpath
... ...
说明:
dir(os):返回该模块所有属性的一个列表
help(os):返回该模块的使用手册
对于文件和目录的管理,shutil模块提供了一个高级的接口,很好用。
例如:
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')
说明:
shutil.copyfile(src, dst):将src代表的文件复制数据给dst代表的文件
shutil.move(src, dst):递归的将src代表的文件或目录移动到dst代表的位置处
2、文件通配符
glob模块提供了一个glob函数,用来支持当前目录下的通配符搜索。
例如:
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
说明:
glob.glob('*.py'):返回当前目录下所有后缀为py的文件。
3、命令行参数
通常情况下我们的脚本都需要命令行参数。这些参数都存储在sys.argv中。 getopt模块使用unix的getopt函数的惯例来处理sys.argv。optparse模块提供了更强大,灵活的功能来处理sys.argv。
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()。
5、字符串模式匹配
re模块为字符串的高级处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的方法。
6、数学处理
math模块提供了处理浮点数的方法。
示例如下:
>>> 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)
4
7、internet访问
Python提供了大量的用于访问internet和处理internet协议的模块。其中最简单的两个是urllib2和smtplib。urllib2用于从url得到数据,smtplib用于发送邮件。
8、日期和时间
datetime模块为用简单和复杂方法去处理日期和时间提供了类。
示例如下:
>>> from datetime import date
>>> now=date.today()
>>> now
datetime.date(2006, 7, 1)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'07-01-06. 01 Jul 2006 is a Saturday on the 01 day of July.'
>>> birthday = date(2006, 7, 1)
>>> age = now - birthday
>>> age.days
0
说明:
date.today():得到当前日期的date对象,如datetime.date(2006, 7, 1)
strftime:将日期时间字符串格式化
date(2006, 7, 1):建一指定日期的日期象
now - birthday:日期对象可以进行算术运算
9、数据压缩
支持数据压缩的模块有:zlib、gzip、bz2、zipfile和tarfile。
下面是一个zlib的例子:
>>> 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
说明:
compress():压缩字符串
decompress():解压缩指定的已被压缩的字符串
crc32():计算给定字符串的CRC-32校验和
10、性能测定
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
说明:
Timer('t=a; a=b; b=t', 'a=1; b=2').timeit():测量语句的执行时间
模块profile和pstats则用于对大块代码的测定。
11、质量控制
开发高质量的软件方法是为每一个所开发的函数写一个测试,并在开发过程中频繁的测试它们。
doctest模块为扫描一个模块和确认内嵌在程序文档字符串中的测试提供了一种手段。这个测试部分我们可以将执行的命令和结果写到函数的文档字符串中。通过这个包含测试部分的文档字符串,我们可以验证我们的函数能否得到想要的结果。
示例如下:
#!/usr/bin/python
#filename: qc.py
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)
def _test():#以下两句必须包含在要测试的模块中
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
说明:>>> print average([20, 30, 70])#要执行的命令
40.0 #预期应有的结果。这就形成了一个测试部分
运行输出如下:
C:/WINDOWS>python f:/pythontools/test/qc.py -v
Trying:
print average([20, 30, 70])
Expecting:
40.0
ok
2 items had no tests:
__main__
__main__._test
1 items passed all tests:
1 tests in __main__.average
1 tests in 3 items.
1 passed and 0 failed.
Test passed.
说明:
C:/WINDOWS>python f:/pythontools/test/qc.py -v:没有-v,如果通过测试,则不作任何显示。
Test passed.:说明测试通过。
unittest模块没有doctest模块那么容易使用,但是它提供了在一个单独文件中进行一套全面测试的手段。
示例如下:
import unittest
from qc import *
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)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests
运行输出如下:
C:/WINDOWS>python f:/pythontools/test/ut.py
.
--------------------------------------------
Ran 1 test in 0.000s
OK
12、强大能力
Python的大量成熟而完善的包体现了它强大的能力。
举例说明如下:
a、xmlrpclib和SimpleXMLRPCServer模块实现了远程建立琐细任务。
b 、email包是一个用来管理email信息的库,包括管理MIME和别的RFC 2822-based信息文档。不像smtplib和poplib,email包有一整套工具用于建立或解码复杂的信息结构和实现internet编码和报头协议。
c、xml.dom和xml.sax包为分析流行的数据交换协议提供了足够的支持。同样,csv模块支持用一般的数据库格式直接读写。这几个模块在python应用程序和别的工具之间提供了非常简单的数据交换。
d、大量的模块提供了对国际化的支持,包括gettext,locale和codec包。
二、专业部分
1、格式化输出
repr模块提供了一个repr()的译本用于大的嵌套的简短显示。
示例如下:
>>> import repr
>>> repr.repr(set('supercalifragilisticexpialidocious'))
"set(['a', 'c', 'd', 'e', 'f', 'g', ...])"
pprint模块提供了为解释器可读的更成熟的对打印内建和用户自定义对象的控制。当打印输出超过一行时,灵活的打印程序会添加换行符和缩进以清楚的显示数据的结构。
示例如下:
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]] ... >>> pprint.pprint(t, width=30) [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
textwrap模块格式化文本的段落以适合给定屏幕的宽度,示例如下:
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it
returns
... a list of strings instead of one big string with newlines to
separate
... the wrapped lines."""
...
>>> print textwrap.fill(doc, width=40)
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
locale模块用于访问具体数据格式的数据库,示例如下:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv()
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
2、模板
string模板包括了一个通用的Template类, 这个类为终端用户的编辑提供了一个简单的语法。
3、处理二进制
struct模块提供了pack()和unpack()函数用于处理可变长的二进制。
4、多线程
threading模块提供了相关的功能。
5、日志
logging提供了一个完整而灵活的日志系统。
6、引用
weakref提供了不创建引用而跟踪对象的工具。它使得内存资源不会造成不合理的浪费。
7、用于列表的工具
用于列表的工具很多,但有时候我们需要根据它们的性能作出选择。这儿有几个模块,它们的性能特点有所区别,这里只列出它们的名称:array,collections,bisect, heapq 。
8、浮点小数算法
decimal模块提供了处理浮点小数算法的手段。
本系列的文章来源是http://www.pythontik.com/html,如果有问题可以与那里的站长直接交流。