python标准库分析_详解Python标准库

d18cce8f0d910d52f4eeb9e62417a321.png

操作系统接口

os 模块提供了大量和操作系统进行交互的函数:>>> import os

>>> os.getcwd()      # 返回当前工作路径

'C:\\Python37'

>>> os.chdir('/server/accesslogs')   # 改变当前工作路径

>>> os.system('mkdir today')   # 调用系统shell自带的mkdir命令

0

请确保使用 import os 而不是 from os import *。第二种方法会导致 os.open() 覆盖系统自带的 open() 函数,这两个函数的功能有很大的不同。

自带的 dir() 和 help() 函数在使用大型模块如 os 时能够成为非常有用的交互工具:>>> import os

>>> dir(os)

>>> help(os)

对于日常的文件或者目录管理任务,shutil 模块提供了更高层次的接口,可以让用户更容易地使用:>>> import shutil

>>> shutil.copyfile('data.db', 'archive.db')

'archive.db'

>>> shutil.move('/build/executables', 'installdir')

'installdir'

文件通配符

glob 模块提供了一个函数,用于在目录中进行通配符搜索,得到一个文件列表。>>> import glob

>>> glob.glob('*.py')

['primes.py', 'random.py', 'quote.py']

命令行参数

常见的工具类脚本经常需要处理命令行参数。 这些参数储存在 sys 模块的 argv 属性中,作为一个列表存在。例如,以下是在命令行运行 python demo.py one two three 的结果输出:>>> import sys

>>> print(sys.argv)

['demo.py', 'one', 'two', 'three']

getopt 模块使用 Unix 约定的 getopt() 函数处理 sys.argv 。更强大、灵活的命令行处理由 argparse 模块提供。

错误输出重定向和退出程序

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()。

字符串匹配

re 模块为字符串的进阶处理提供了正则表达式的工具。对于复杂的匹配操作,正则表达式给出了简洁有效的解决方案:>>> import re

>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')

['foot', 'fell', 'fastest']

>>> re.sub(r'(\b[a-z] ) \1', r'\1', 'cat in the the hat')

'cat in the hat'

当只需要简单的功能时,采用字符串的方法更简洁易懂:>>> 'tea for too'.replace('too', 'two')

'tea for two'

数学库

math 模块可以访问 C 语言编写的浮点类型数学库函数:>>> import math

>>> math.cos(math.pi / 4)0.70710678118654757

>>> math.log(1024, 2)10.0

random 模块提供了进行随机选择的工具:>>> import random

>>> 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 :>>> 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')  # 解码.

...         if 'EST' in line or 'EDT' in line:  # 查看是否是EST或EDT时间

...             print(line)


Nov. 25, 09:43:32 PM EST

>>> import smtplib

>>> server = smtplib.SMTP('localhost')

>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',

... """To: jcaesar@example.org

... From: soothsayer@example.org

...

... Beware the Ides of March.

... """)

>>> server.quit()

日期和时间

datetime 模块提供了多种用于简单处理和复杂处理日期和时间的类。支持日期时间的运算、时间解析、格式化输出等,实现上重点优化了效率。模块也支持了时区的概念。>>> # 日期对象能非常方便的构建和输出

>>> from datetime import date

>>> now = date.today()

>>> now

datetime.date(2003, 12, 2)

>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")

'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # 支持日期运算

>>> birthday = date(1964, 7, 31)

>>> age = now - birthday

>>> age.days

14368

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值