详解Python标准库

操作系统接口
os 该模块提供了大量与操作系统交互的函数:
>>>importos
>>>os.getcwd()#返回当前工作路径
'C:\Python37'
>>>os.chdir('/server/accesslogs')#改变当前的工作路径
>>>os.system('mkdirtoday')#调用系统shell自带的mkdir命令
0请确保使用 import os 而不是 from os import *。第二种方法会导致 os.open() 自带覆盖系统 open() 函数,这两个函数的功能非常不同。
自带的 dir() 和 help() 在大模块中使用函数 os 成为一种非常有用的交互工具:
>>>importos >>>dir(os) <返回包含os模块所有函数的listt> >>>help(os) <返回os模块docstring生成的手册>
Shutil模块为日常文件或目录管理任务提供了更高层次的接口,使用户更容易使用:
>>>importshutil
>>>shutil.copyfile('data.db','archive.db')
'archive.db'
>>>shutil.move('/build/executables','installdir')
'installdir'文件通配符
glob 该模块为搜索目录中的通配符提供了一个函数,以获得文件列表。
>>>importglob
>>>glob.glob('*.py')
['primes.py','random.py','quote.py']命令行参数
常见的工具脚本通常需要处理命令行参数。 存储这些参数 sys 模块的 argv 在属性中,作为列表存在。例如,以下是命令操作 python demo.py one two three 结果输出:
>>>importsys >>>print(sys.argv) ['demo.py','one','two','three']
getopt 模块使用 Unix 约定的 getopt() 函数处理 sys.argv 。处理更强大、更灵活的命令行的原因 argparse 模块提供。
错误输出重定向和退出程序
sys 模块有 stdin,stdout 和 stderr 这些属性。即使处理警告和错误信息,后者也非常有用 stdout 被重定向,或者可以看到错误的信息:
>>>sys.stderr.write('Warning,logfilenotfoundstartinganewone\n')
Warning,logfilenotfoundstartinganewone退出程序最直接的方法是使用syss.exit()。
字符串匹配
re 该模块为字符串的高级处理提供了正则表达式工具。正则表达式为复杂的匹配操作提供了简单有效的解决方案:
>>>importre >>>re.findall(r'\bf[a-z]*','whichfootorhandfellfastest') ['foot','fell','fastest'] >>>re.sub(r'(\b[a-z]+)\1',r'\1','catinthethehat') 'catinthehat'
当只需要简单的功能时,使用字符串的方法更容易理解:
>>>'teafortoo'.replace('too','two')
'teafortwo'数学库
math 可访问模块 C 语言编写浮点类型数学库函数:
>>>importmath >>>math.cos(math.pi/4)0.70710678118654757 >>>math.log(1024,2)10.0
random模块提供了随机选择的工具:
>>>importrandom >>>random.choice(['apple','pear','banana']) 'apple' >>>random.sample(range(100)#不重复抽样 [30,83,16,4,81,41,50,18,33] >>>random.random()#随机float类型输出 0.17970987693706186 >>>random.randrange(6)#从range(6)的返回范围内产生随机数 4
网络请求
有很多模块可以访问网络,并根据各自的网络协议处理数据。最简单的两个是从 URL 获取数据的 urllib.request 并用于发送邮件 smtplib :
>>>fromurllib.requestimporturlopen
>>>withurlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl')asresponse:
...forlineinresponse:
...line=line.decode('utf-8')#解码.
...if'EST'inlineor'EDT'inline:#检查是EST还是EDT时间
...print(line)
<BR>Nov.25,09:43:32PMEST
>>>importsmtplib
>>>server=smtplib.SMTP('localhost')
>>>server.sendmail('soothsayer@example.org','jcaesar@example.org',
..."""To:jcaesar@example.org
...From:soothsayer@example.org
...
...BewaretheIdesofMarch.
...""")
>>>server.quit()日期和时间
datetime 该模块提供了多个类别,用于简单处理和复杂处理日期和时间。支持日期和时间的计算、时间分析、格式化输出等,重点优化效率。该模块还支持时区概念。
>>>#日期对象可以非常方便地构建和输出
>>>fromdatetimeimportdate
>>>now=date.today()
>>>now
datetime.date(2003,12,2)
>>>now.strftime("%m-%d-%y.%d%b%Yisa%Aonthe%ddayof%B.")
'12-02-03.02Dec2003isaTuesdayonthe02dayofDecember.'
>>>#支持日期运算
>>>birthday=date(1964,7,31)
>>>age=now-birthday
>>>age.days
14368 