[译]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解释器中退出然后重新进入,之前定义的名字(函数和变量)都丢失了.因此,如果你想写长一点的程序,使 ...
随机推荐
- android 开发-数据存储之文件存储
android的文件存储是通过android的文件系统对数据进行临时的保存操作,并不是持久化数据,例如网络上下载某些图片.音频.视频文件等.如缓存文件将会在清理应用缓存的时候被清除,或者是应用卸载的时 ...
- C#获得字符串首字符字母(大写)
/// <summary> /// 获得字符串首字符字母(大写): /// </summary> /// <param name="cnChar"&g ...
- kafka基础一
基本概念: 消息系统的组成由生产者,消费者以及存储系统.消费者从存储系统中读取生产者生产的消息.Kafka作为分布式的消息系统支持多个生产者多个消费者,写消息时允许多个生产者写到同一个Partitio ...
- String与Date转换
public class TimeTraining { public static void changeStr(String str){ str = "137878"; } pu ...
- vue实现选中列表功能
<template> <div> <ul v-for="prop in items"> <dt>{{prop.name}}</ ...
- Android学习笔记1——Android开发环境配置
一.JDK配置 Android是基于Java进行开发的,首先需要在电脑上配置JDK(Java Development Kit).在http://www.androiddevtools.cn/下载对应系 ...
- 通过 java的 esl 连接 freeswitch
一.目标修改event_socket配置,使之能够建立远端ESL链接. 二.步骤 1. vim ../autoload_configs/event_socket.conf.xml 2. 默认的监听地址 ...
- 解析ASPX网页__doPostBack分页的网页table数据
由于急于上线的功能要去客服系统里抓取数据进行验证,客服方面又没有时间开发EDI接口给到我,所以用了本办法:爬人家web系统上的数据进行分析. 由于客服的web系统用ASP.Net的__doPostBa ...
- Nginx源码安装及调优配置(转)
导读 由于Nginx本身的一些优点,轻量,开源,易用,越来越多的公司使用nginx作为自己公司的web应用服务器,本文详细介绍nginx源码安装的同时并对nginx进行优化配置. Nginx编译前 ...
- 【洛谷4011】孤岛营救问题(状压SPFA)
点此看题面 大致题意: 有一个\(N*M\)的四联通迷宫,相邻两个可能互通,可能有一扇门,也可能有一堵墙.对于第\(i\)类的门,你需要有第\(i\)类的钥匙才可以通过.问你从\((1,1)\)到达\ ...