详解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模块所有函数的list>
>>>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

退出程序最直接的方法是用sys.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),10)#不重复抽样
[30,83,16,4,8,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()

日期和时间

>>>#日期对象能非常方便的构建和输出
>>>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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。