操作系统接口
os模块提供了与操作系统关联的函数
>>> import os
>>> os.getcwd()
>>> os.chdir('/')
>>> os.getcwd()
'/'
>>> os.system('mk /root/test')
sh: mk: command not found
32512
>>> os.system('mkdir /root/test')
0
最好使用import os风格,非from os import * 可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。
其中dir()和help()函数很有用,其中dir()列出了所有函数的一个列表,help是大量帮助信息页
对日常的文件和目录管理任务,:mod:shutil模块一个易于使用的高级接口比如复制移动文件:
>>> import shutil
>>> shutil.copyfile('2.txt','3.txt')
'3.txt'
>>> shutil.move('2.txt','4.txt')
'4.txt'
文件通配符
glob模块提供了一个函数用于从目录通配符搜索中声称文件列表:
>>> import glob
>>> glob.glob('*.py')
['fun1.py', 'hello.py', 'fun3.py', '2.py', '1.py']
命令行参数
通用工具脚本经常调用命令行参数,这些命令行参数以链表形式存储于 sys 模块的 argv 变量
>>> import sys
>>> print(sys.argv)
['']
错误输出重定向和程序终止
sys有stdin,stdout和stderr属性,即使在stdout 被重定向时,后者也可以用于显示警告和错误信息
>>> sys.stderr.write('Warning,log file not found\n')
Warning,log file not found
27
字符串正则匹配
re模块为高级字符串处理提供了正则表达式工具
>>> import re
>>> re.findall(r'f[a-z]*','food,file,abc,fast')
['food', 'file', 'fast']
>>> re.sub(r'(\b[a-z]+) \1',r'\1','a abc abc def')
'abc abc def'
>>> re.sub(r'(\b[a-z]+) \1',r'\1','b abc abc def')
'b abc def'
数学
math为浮点运算提供了对底层C函数库的访问,random提供了产生随即数的工具:
>>> import math
>>>
>>> math.cos(math.pi/4)
0.7071067811865476
>>> math.log(16,2)
4.0
>>>
>>> import random
>>> random.choice(['a','b','c'])
'c'
>>> random.sample(range(10),10)
[4, 7, 9, 6, 3, 8, 0, 5, 2, 1]
>>> random.random()
0.756815126534027
>>> random.randrange(10)
3
>>> random.randrange(10)
访问互联网
python提供了访问互联网和处理网络通信协议,最简单的两个是用于处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib:
比如
>>> from urllib.request import urlopen
>>> for line in urlopen('XXX'):
... line = line.decode('utf-8') # Decoding the binary data to text.
... if 'error' in line or 'warning' in line: # look for Eastern Time
... print(line)
...
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('xxx@qq.com', 'xxx1@qq.com',
... """To: xxx@qq.com
... From: xxx1@qq.com
...
...
... """)
>>> server.quit()
日期和时间
datetime模块提供了日期和时间按处理的方法
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2017, 5, 13)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'05-13-17. 13 May 2017 is a Saturday on the 13 day of May.'
>>> b = date(1960,1,1)
>>> age=now-b
>>> age.days
20952
数据压缩
支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile
>>> import zlib
>>> s = b'my name is china, i like it'
>>> len(s)
27
>>> t=zlib.compress(s)
>>> len(t)
34
>>> zlib.decompress(t)
b'my name is china, i like it'
>>> zlib.crc32(s)
2565214701
性能度量
Python 提供了度量同样问题不同方法的性能测试
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.030256840007496066
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.06578436600102577
测试模块
高质量软件方法之一是为每个函数开发测试代码,并且开发过程中经常测试。
doctest模块提供了一个工具