操作系统接口
模块提供一系列与操作系统进行交互的函数。
import os
os.getcwd() # 返回当前工作目录
os.chdir('/server/accesslogs') # 修改当前工作目录
os.system('mkdir today') # 在系统shell中运行mkdir命令
确保使用 import os 而不是 from os import *.它将导致
诸如os等大模块工作时,一些内建函数
import os
dir(os)
help(os)
针对日常的文件、目录的管理任务,
import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')
文件通配符
glob 模块提供了通过通配符列出文件列表的功能.
import glob
glob.glob('*.py')
命令行参数
常见的实用脚本通常需要处理命令行参数,这些参数以list的形式存储在sys 模块的argv属性中.
使用下面的代码运行python demo.py one two three`
import sys
print(sys.argv)
结果为
['demo.py', 'one', 'two', 'three']
getopt() 函数处理sys.argv,argparse 模块提供了更强大易拓展的命令行处理流程.
错误输出重定向&程序终止
[sys]模块拥有 stdin,stdout和stderr属性,stderr是很有用的,即使在stdout被重定向后,由它发出警告和错误信息也都是可见的.
sys.stderr.write('Warning, log file not found starting a new one\n')
sys.exit()是停掉脚本最直接的方式
字符模式匹配
import re
re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
当仅仅需要一些简单的功能时,string 方法是更合适的选择,它的可读性更高,更易进行debug.
'tea for too'.replace('too', 'two')
数学运算
import math
math.cos(math.pi / 4)
math.log(1024, 2)
random 模块提供了进行随机选择的工具.
import random
random.choice(['apple', 'pear', 'banana'])
random.sample(range(100), 10) # sampling without replacement
random.random() # random float
random.randrange(6) # random integer chosen from range(6)
statistic模块计算数值的基本统计属性(均值,中位数,方差等)
import statistics
data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
statistics.mean(data)
statistics.median(data)
statistics.variance(data)
SciPy 工程有很多进行数值运算的模块
接入互联网
有很多模块可用于接入互联网并处理互联网协议,这里列举两个最简单的:
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)
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()
(注意: 这个例子需要localhost运行一个邮件服务)
日期和时间
# dates are easily constructed and formatted
from datetime import date
now = date.today()
now
now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
# dates support calendar arithmetic
birthday = date(1964, 7, 31)
age = now - birthday
age.days
数据压缩
import zlib
s = b'witch which has which witches wrist watch'
len(s)
t = zlib.compress(s)
len(t)
zlib.decompress(t)
zlib.crc32(s)
性能衡量
一些Python用户对了解解决同一问题的不同解决方式的实际性能有着很深的兴趣,Python为直接地这些问题提供了测量工具。
例如:直接使用tuple装包和开包特性替代传统的参数交换方式是很有吸引力的,
from timeit import Timer
Timer(‘t=a; a=b; b=t’, ‘a=1; b=2’).timeit()
Timer(‘a,b = b,a’, ‘a=1; b=2’).timeit()
与
质量控制
开发高质量的软件的一种方法是在开发软件的过程中为每个function编写测试,并在开发过程中频繁的运行这些测试.
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
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
内置电池
Python有一个’内置电池’理念,它能很好地通过一些成熟并且健壮的package表现出来。例如:
emailpackage是一个负责管理邮件消息的库,包含MIME和其他RFC2822-base消息文件,不像smtplib和piplib一样真正的进行消息收发,email package有一个复杂工具集来构建或解码复杂消息结构(包括附件)及实现网络编码和报头协议
json为解析这种流行的数据交换格式提供了强大的支持,csv支持以逗号进行分隔值的形式进行文件的读写,通常支持数据库和电子表格,xml.etree.ElementTree, xml.dom 和 xml.sax对xml程序提供支持,这些package极大地简化了Python和其他工具间的数据交换。
sqlite3是对SQLite数据库库的包装,提供了一个持久性数据库,可以使用稍微不标准SQL语法对数据库进行更新和访问。