[译]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解释器中退出然后重新进入,之前定义的名字(函数和变量)都丢失了.因此,如果你想写长一点的程序,使 ...
随机推荐
- 如何设计企业移动应用 by宋凯
移动应用设计内部培训 by宋凯 企业移动应用的特点:简约.效率.增强ERP与环境的结合.及时.安全.企业内社交. 一句话定义你的移动应用:然后围绕这句话来设计你的APP. 一:如何定义你的应用: 1, ...
- js中的onclick事件传参需要注意的问题
如果参数是数值类型可以直接传,如果是字符串类型需要在字符串前后加上双引号,双引号需要转义 如 onclick="test(0)"; 直接传值 参数为数值 onclick=&quo ...
- 4 - Channelhandler和ChannelPipeline
4.1 Channelhandler 4.1.1 Channel声明周期(状态事件) 方法 描述 ChannelUnregistered Channnel已创建,但是未注册到EventLoop Cha ...
- pat1061. Dating (20)
1061. Dating (20) 时间限制 50 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Sherlock Holmes ...
- 最简实例演示asp.net5中用户认证和授权(2)
上接最简实例演示asp.net5中用户认证和授权(1) 基础类建立好后,下一步就要创建对基础类进行操作的类了,也就是实现基础类的增删改查(听起来不太高大上),当然,为了使用asp.net5的认证机制, ...
- ubuntu下apk的反编译
今天调试一个程序的时候,因为需要上传数据到服务器,但是程序太过久远了,服务器上传的地址就忘记了,但是源码又不在我这里,因为要的急所以就被逼无奈的情况下想到了反编译,我用的是Linux Mint 14. ...
- JAVA反射练习
JAVA反射练习 题目 实现一个方法 public static Object execute(String className, String methodName, Object args[]) ...
- 获取hudson持续构建编译结果的一种方法
作者:朱金灿 来源:http://blog.csdn.net/clever101 很多时候使用hudson结合VisualStudio进行持续构建后需要获取持续构建的编译结果,通过编译结果来知道哪些项 ...
- C#中描述mssql中DateTime的最小值、最大值
首先引用System.Data.SqlTypes 最小值:SqlDateTime.MinValue.Value 最大值:SqlDateTime.MaxValue.Value
- 不该被忽视的CoreJava细节(一)
一.系列文章导言 <不该被忽视的CoreJava细节>系列文章将会持续更新.我希望自己通过这一系列文章的写作,能与读者一起进步,逐步完善对Java体系结构的了解. 二.本期关注点 几乎翻看 ...