[译]The Python Tutorial#10. Brief Tour of the Standard Library
来源:互联网 发布:windows tv box 编辑:程序博客网 时间:2024/06/05 12:12
[译]The Python Tutorial#Brief Tour of the Standard Library
10.1 Operating System Interface
os模块为与操作系统交互提供了许多函数:
>>> import os>>> os.getcwd() # Return the current working directory'C:\\Python36'>>> os.chdir('/server/accesslogs') # Change current working directory>>> os.system('mkdir today') # Run the command mkdir in the system shell0
确保使用import os
而不是from os import *
。后者会导入os.open()
并屏蔽效率更高的内置函数open
。
使用如os
一般的大型模块时,内置函数dir()
和help()
函数提供的交互式帮助很有用:
>>> import os>>> dir(os)<returns a list of all module functions>>>> help(os)<returns an extensive manual page created from the module's docstrings>
对于日常文件和目录的管理任务,shutil
模块提供了更高更次的接口,更容易使用:
>>> import shutil>>> shutil.copyfile('data.db', 'archive.db')'archive.db'>>> shutil.move('/build/executables', 'installdir')'installdir'
10.2 File Wildcards
glob
模块提供了函数,该函数在指定目录下使用通配符搜索文件,并返回符合的文件名列表:
>>> import glob>>> glob.glob('*.py')['primes.py', 'random.py', 'quote.py']
10.3 Command Line Arguments
一般的工具脚本通常需要处理命令行参数。命令行参数作为列表存储在sys
模块的argv属性中。例如以下是在命令行运行python demo.py one two three
输出结果:
>>> import sys>>> print(sys.argv)['demo.py', 'one', 'two', 'three']
getopt
模块使用Unix的getopt()
函数约定处理sys.argv。更多强大并灵活的命令行处理由argparse模块提供。
10.4 Error Output Redirection and Program Termination
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()
。
10.5 String Pattern Matching
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'
10.6 Mathematics
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) # sampling without replacement[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]>>> random.random() # random float0.17970987693706186>>> random.randrange(6) # random integer chosen from range(6)4
statistics
模块提供了计算数字数据基础统计属性(如均值,中位数,方差等)的方法:
>>> import statistics>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]>>> statistics.mean(data)1.6071428571428572>>> statistics.median(data)1.25>>> statistics.variance(data)1.3720238095238095
SciPy 项目
10.7 Internet Access
Python提供了许多用于网络资源访问以及互联网协议处理的模块。最简单的两个是用于从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') # Decoding the binary data to text.... if 'EST' in line or 'EDT' in line: # look for Eastern Time... 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()
(注意第二个示例需要在本地运行的邮件服务)
10.8 Dates and Times
datetime
模块提供了以简单或者复杂方式计算时间以及日期的类。支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。该模块同时支持时区处理。
>>> # dates are easily constructed and formatted>>> from datetime import date>>> now = date.today()>>> nowdatetime.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.'>>> # dates support calendar arithmetic>>> birthday = date(1964, 7, 31)>>> age = now - birthday>>> age.days14368
10.9 Data Compression
以下模块直接支持通用数据的打包和压缩格式:zlib, gzip, bz2, lzma, zipfile 以及 tarfile.
>>> import zlib>>> s = b'witch which has which witches wrist watch'>>> len(s)41>>> t = zlib.compress(s)>>> len(t)37>>> zlib.decompress(t)b'witch which has which witches wrist watch'>>> zlib.crc32(s)226805979
10.10 Performance Measurement
一些Python开发者对同一个问题的不同解决方案的相对性能有极大兴趣。Python为此提供了一个测量工具。
例如,使用元组的打包和解包特性代替传统方法实现值的交换是很诱人的。timeit
模块能够快速证实序列解包更快:
>>> from timeit import Timer>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()0.57535828626024577>>> Timer('a,b = b,a', 'a=1; b=2').timeit()0.54962537085770791
不同于timeit
的细粒度,profile
以及pstas
模块提供了适用于大型代码块的性能测量工具。
10.11 Quality Control
开发高质量软件的一种方式是在每一个函数编写时,为其编写测试用例,并且在开发过程中经常运行这些测试用例。
doctest
模块提供了一个工具,该工具扫描模块并验证内嵌入程序文档字符串中的测试。测试的结构非常简单,就像复制粘贴一个附带返回值的典型函数调用一样。为使用者提供调用示例,从而增强了文档,同时允许doctest模块确保代码如文档描述那样的正确性:
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 doctestdoctest.testmod() # automatically validate the embedded tests
unittest
不像doctest模块那样简单,但是它允许在单独的文件中维护复杂的测试集合:
import unittestclass 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
10.12 Batteries Included
Python有“自带电池”的哲学。这一点可以从Python自带庞大包提供的大量功能看出来。例如:
- xmlrpc.server和
xmlrpc.client
模块让远程调用变得非常简单,尽管名字中有xml,但是在使用时无需xml的知识,也不需要处理xml。 - email包是管理邮件信息的库,包括MIME其他以及基于RFC-32的信息文档。与实际发送和接受邮件的
smtplib
和poplib
不同,emial包拥有一个完整的工具集合,该工具集包含构造以及解码复杂消息结构(包括附件)以及实现网络编码和头协议等功能。 - json包提供了解析json这种流行的数据交换格式的支持。csv支持直接读写通用数据格式文件,包括数据库和表格文件。xml.etree.ElementTree, xml.dom 以及 xml.sax包支持XML的处理。这些模块极大简化了Python应用和其他工具之间的数据交换。
- sqlite3模块是对SQLite数据库的包装库,该模块提供了一个持久数据库,可以通过稍微不标准的sql语法访问和更新数据库。
- 国际化由一系列模块支持,包括: gettext, locale, 以及codecs包。
- [译]The Python Tutorial#10. Brief Tour of the Standard Library
- [译]The Python Tutorial#11. Brief Tour of the Standard Library — Part II
- [python3教程]第十章.标准库简介(Brief Tour of The Standard Library)
- The Python Standard Library
- PyCon 2011 - Hidden Treasures of the Python Standard Library
- A Brief Tour of the Trees and Forests
- A Brief Tour of the Trees and Forests
- Python标准库The Python Standard Library
- The C++ Standard Library Extensions: A Tutorial and Reference
- 读书摘要:C++ Standard Library, The: A Tutorial and Reference
- The C++ Standard Library Extensions: A Tutorial and Reference
- The Standard C Library
- PyCon 2011 - Hidden Treasures of the Python Standard Library - Source code
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 自定义sqlite3数据表字段数据类型
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 模拟hmac摘要算法的实现
- PyCon 2011 - Hidden Treasures of the Python Standard Library - json序列化操作
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 全局异常捕获
- PyCon 2011 - Hidden Treasures of the Python Standard Library - logging日志处理
- 【HDU 6050 Funny Function】 + 数学
- ClassLoader解惑
- WordPress忘记密码找回登录密码的四种行之有效的方法
- 扎克伯克怒怼马斯克引围观_你支持谁?
- 如何更换及调整csdn头像
- [译]The Python Tutorial#10. Brief Tour of the Standard Library
- NOIP2016 T3 换教室
- CodeIgniter框架源码学习之钩子类--Hooks.php
- 应用经验 技巧 C#中的Dictionary作为人机语言转换的桥梁
- eclipse工程视图
- 页面的返回操作
- 关于逻辑运算符&、|和&&、||的区别
- [译]The Python Tutorial#12. Virtual Environments and Packages
- 《Kali+Linux渗透测试的艺术》学习总结之----Kali Linux简介