[译]The Python Tutorial#10. Brief Tour of the Standard Library
[译]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 shell
0
确保使用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 float
0.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 项目 https://scipy.org 提供了许多用于数字计算的模块
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()
>>> 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.'
>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
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 doctest
doctest.testmod() # automatically validate the embedded tests
unittest不像doctest模块那样简单,但是它允许在单独的文件中维护复杂的测试集合:
import unittest
class 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
[译]The Python Tutorial#Brief Tour of the Standard Library - Part II 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...
- [译]The Python Tutorial#12. Virtual Environments and Packages
[译]The Python Tutorial#Virtual Environments and Packages 12.1 Introduction Python应用经常使用不属于标准库的包和模块.应 ...
- [译]The Python Tutorial#7. Input and Output
[译]The Python Tutorial#Input and Output Python中有多种展示程序输出的方式:数据可以以人类可读的方式打印出来,也可以输出到文件中以后使用.本章节将会详细讨论 ...
- [译]The Python Tutorial#8. Errors and Exceptions
[译]The Python Tutorial#Errors and Exceptions 到现在为止都没有过多介绍错误信息,但是已经在一些示例中使用过错误信息.Python至少有两种类型的错误:语法错 ...
- [译]The Python Tutorial#5. Data Structures
[译]The Python Tutorial#Data Structures 5.1 Data Structures 本章节详细介绍之前介绍过的一些内容,并且也会介绍一些新的内容. 5.1 More ...
- [译]The Python Tutorial#4. More Control Flow Tools
[译]The Python Tutorial#More Control Flow Tools 除了刚才介绍的while语句之外,Python也从其他语言借鉴了其他流程控制语句,并做了相应改变. 4.1 ...
- [译]The Python Tutorial#2. Using the Python Interpreter
[译]The Python Tutorial#Using the Python Interpreter 2.1 Invoking the Interpreter Python解释器通常安装在目标机器的 ...
- [译]The Python Tutorial#1. Whetting Your Appetite
[译]The Python Tutorial#Whetting Your Appetite 1. Whetting Your Appetite 如果你需要使用计算机做很多工作,最终会发现很多任务需要自 ...
- [译]The Python Tutorial#6. Modules
[译]The Python Tutorial#Modules 6. Modules 如果你从Python解释器中退出然后重新进入,之前定义的名字(函数和变量)都丢失了.因此,如果你想写长一点的程序,使 ...
随机推荐
- [PHP]php发布和调用Webservice接口的案例
分两步走:1.服务端发布接口;2.客户端调用方法 1.服务端发布接口: 需要nusoap工具,下载地址:http://sourceforge.net/projects/nusoap/ 下载完和要发布接 ...
- volatile底层原理详解
今天我们聊聊volatile底层原理: Java语言规范对于volatile定义如下: Java编程语言允许线程访问共享变量,为了确保共享变量能够被准确和一致性地更新,线程应该确保通过排它锁单独获得这 ...
- HttpClient向后端的WebAPI工程发送HTTP的Post请求时,返回超过了最大请求长度的异常的解决方法
文章中的内容以及解决思路参考(转载)的 http://www.jb51.net/article/88698.htm 在WPF项目中通过HttpClient向后端的WebAPI工程发送HTTP的Post ...
- js加密,三种编码方式
·escape(69个):*/@+-._0-9a-zA-Z ·encodeURI(82个):!#$&’()*+,/:;=?@-._~0-9a-zA-Z ·encodeURI ...
- ssm(Spring、Springmvc、Mybatis)实战之淘淘商城-第九天(非原创)
文章大纲 一.课程介绍二.今日功能介绍三.项目源码与资料下载四.参考文章 一.课程介绍 一共14天课程(1)第一天:电商行业的背景.淘淘商城的介绍.搭建项目工程.Svn的使用.(2)第二天:框架的整合 ...
- Vue-watch选项
Vue ----watch 选项 用于 监听数据变化: <!DOCTYPE html> <html lang="en"> <head> < ...
- Thread.sleep 与Thread.currentThread.sleep
参考博客: https://blog.csdn.net/guangyinglanshan/article/details/51645053 公司项目近段时间要使用thread, 个人想去了解Threa ...
- iOS 当使用FD_FullscreenPopViewController的时候遇到scrollView右滑手势无法使用的解决
当我们在ViewController中有scrollView的时候, 可能会遇到右滑无法响应返回手势, 有以下解决办法: 自定义scrollView, 实现该scrollView的以下方法即可: @i ...
- w3cschool中jQuery测试结果总结
1.jQuery 是 W3C 标准. 2.$("div#intro .head") 选择器选取:class="intro" 的任何 div 元素中的首个 id= ...
- JavaScript基础:(加号,数值转换,布尔转换)
JavaScript中加号运算符"+" 运算过程理解 1) 如果其中一个操作数是对象,则对象会遵循对象到原始值的转换规则转换为原始值.日期对象通过toString()方法执行转换, ...