python标准库-第一部分

来源:互联网 发布:vscode 切换大小写 编辑:程序博客网 时间:2024/06/01 09:05

本文译自https://docs.python.org/2.7/tutorial/。完全是出于个人兴趣翻译的,请勿追究责任。另外,谢绝商业牟利。刊印请与本人和原作者联系,无授权不得刊印,违者必究其责任。如需转发,请注明来源,并保留此行,尊重本人的劳动成果,谢谢。

来源:CSDN博客

作者:奔跑的QQEE

python 版本:2.7.13

(本文有删改)

python标准库-第一部分

一、操作系统接口

os模块为与操作系统交互提供了许多方法。例:

>>> import os>>> os.getcwd()      # 返回当前工作目录'C:\\Python26'>>> os.chdir('/server/accesslogs')   # 改变当前工作目录>>> os.system('mkdir today')   # R运行命令 mkdir0

使用import os而不要使用from os import *。这样在执行open()方法时可以保证调用的是os.open()方法而不是内置的open()方法。这两种方法作用完全不同。os.open(file,flags[,mode])打开文件并根据其提供的flags设置对应的flags,根据提供的mode设置对应的modeopen(name[,mode[,buffering]])打开文件并返回文件对象

使用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')    # 复制文件到新文件>>> shutil.move('/build/executables', 'installdir') # 移动文件到新目录

二、文件通配符

glob模块提供了使用通配符查找文件列表的方法。例:

>>> import glob>>> glob.glob('*.py')['primes.py', 'random.py', 'quote.py']

三、命令行参数

经常需要处理命令行参数。这些参数以列表的形式存储在sys模块的argv属性中。下例结果是在命令行中执行完python demo.py one two three后得到的:

>>> import sys>>> print sys.argv['demo.py', 'one', 'two', 'three']

getopt模块处理sys.argv是通过使用unix系统的getopt()方法。argparse模块提供了更为强大灵活的命令行处理方法。

四、错误结果输出与终端操作

sys模块有三个属性:stdin,stdout,stderr。当 stdout被定向时,可以用stderr输出错误提示。例:

>>> 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)0.70710678118654757>>> math.log(1024, 2)10.0

random模块提供了产生随机的方法。

>>> import random>>> random.choice(['apple', 'pear', 'banana'])'apple'>>> random.sample(xrange(100), 10)   # 不放回抽样[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]>>> random.random()    # 随机浮点数0.17970987693706186>>> random.randrange(6)    # [0,6) 范围内产生随机整数4

七、网络接口

python中有很多访问互联网,处理网络协议的模块。有两个最简单的模块:urllib2,smtplib

urllib2用来检索指定URL代表的位置中的数据。smtplib用来发送邮件。例:

>>> import urllib2>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):...     if 'EST' in line or 'EDT' in line:  # 查找东部时间...         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()>>> 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.'>>> # 支持日期计算>>> birthday = date(1964, 7, 31)>>> age = now - birthday>>> age.days14368

九、数据压缩

python支持一般的压缩数据格式。不同模块实现不同压缩格式,如zlibgzipbz2zipfiletarfile。例:

>>> import zlib>>> s = 'witch which has which witches wrist watch'>>> len(s)41>>> t = zlib.compress(s)>>> len(t)37>>> zlib.decompress(t)'witch which has which witches wrist watch'>>> zlib.crc32(s)226805979

十、性能测定

python提供了用于测定性能的工具。例:

>>> 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模块,pstats模块。不过后两者用于测定大块代码段中关键部分代码的性能。

十一、质量控制

保证开发出高质量软件的方法之一是测试。这一方法要在开发过程中反复实行。

doctest模块提供了检测程序中文本字符的方法。例:

>>>def average(values):...    """Computes the arithmetic mean of a list of numbers.......    >>> print average([20, 30, 70])...    40.0...    """...    return sum(values, 0.0) / len(values)>>>import doctest>>>doctest.testmod()   TestResults(failed=0, attempted=1)  # 测试的结果

unittest模块支持更为全面的测试。例:

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() ----------------------------------------------------------------------Ran 0 tests in 0.000sOK
阅读全文
0 0
原创粉丝点击