知行编程网知行编程网  2022-12-01 10:30 知行编程网 隐藏边栏  8 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于详解Python标准库的相关知识,包括python的第三方库和标准库,以及python常用标准库这些编程知识,希望对大家有参考作用。

详解Python标准库


操作系统接口

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)
<返回一个包含os模块所有函数的list>
>>> help(os)
<返回一个从os模块docstring产生的手册>

对于日常的文件或目录管理任务,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 2 3 的输出:

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

<BR>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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享