kidys 发表于 2015-4-24 10:35:52

「学习笔记——Python」Python标准库简明教程

10 Python标准库简明教程



Table of Contents




[*]1 操作系统接口
[*]2 文件通配符
[*]3 命令行参数
[*]4 错误输出重定向和程序终止
[*]5 字符串模式匹配
[*]6 数学
[*]7 Internet访问
[*]8 日期和时间
[*]9 数据压缩
[*]10 性能测量
[*]11 质量控制



1 操作系统接口


  os 模块提供了一系列与系统交互的模块:

>>> os.getcwd()# Return the current working directory
'/home/minix/Documents/Note/Programming/python/lib1'
>>> os.chdir('~/python') # Change current working directory
Traceback (most recent call last):
File "", line 1, in
OSError: No such file or directory: '~/python'
>>> os.chdir('/home/minix/python') # Change current working directory
>>> os.system('mkdir tos')
0
>>> os.system('ls')
classes      errorAexception       learnPythonpythonInterpreter
controlFlow    informalIntroductionlib1         tos
dataStructureio                  modules
0

  注意


[*]注意使用 import os, 而非 from os import *.否则os.open()会覆盖内置的open()函数
[*]路径要写全路径哦~
  shutil 模块提供了易于使用的接口,方便我们日常的文件管理工作

>>> os.system('touch data.db')
0
>>> os.system('ls')
data.db
0
>>> import shutil
>>> shutil.copy('data.db', 'archive.db')
>>> os.system('ls')
archive.dbdata.db
0



2 文件通配符


  glob 模块提供了使用通配符获取文件名列表的方式:

>>> os.system ('ls')
archive.dbdata.dbfoo.cpp
0
>>> import glob
>>> glob.glob('*.db')
['archive.db', 'data.db']



3 命令行参数


  通常使用脚本时会给它提供参数,通过sys模块的argv属性可以得到这些参数

#demo.py
import sys
print sys.argv

  这样,在命令行执行时会得到:

$ python demo.py one two three
['demo.py', 'one', 'two', 'three']

  geropt 模块使用 Unix的 getopt()函数的方式处理sys.argv. 更多强大灵活的命令行处理方式可以在 argparse 模块中找到。



4 错误输出重定向和程序终止


  sys 模块还提供了三个属性:stdin,stdout,和stderr.当stdout被重定向时,stderr可以显示错误和警告.

>>> import sys
>>> sys.stderr.write('Warning, long file not found\n')
Warning, long file not found

  结束一个脚本最直接的方式是使用 sys.exit()



5 字符串模式匹配


  re 模块为高级字符串处理提供了正则表达式工具.对一些复杂的匹配的操作,正则表达式通常能提供 最优的解决方案:

>>> re.sub(r'(\b+) \l', r'\l', 'cat in the the hat hat')
'cat in the the hat hat'

  当只需要一些简单的功能时,string 方法是最好的,因为它们容易阅读和调试

>>> 'tea for too'.replace('too', 'two')
'tea for two'



6 数学


  math 模块提供了访问底层C函数库中浮点处理函数的功能:

>>> import math
>>> math.cos(math.pi / 4.0)
0.7071067811865476
>>> math.log(1024, 2)
10.0

  random 模块提供了用于随机选择的工具

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'banana'
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(xrange(100), 10)

>>> random.sample(xrange(100), 10)

>>> random.random()
0.4976690748939975
>>> random.random()
0.10626734770387691
>>> random.randrange(10)
6
>>> random.randrange(10)
9



7 Internet访问


  python中有一系列模块用于访问internet,处理internet协议.其中最简单的是urllib2和smtplib,前者用于从URL接收数据, 后者可以发送邮件.



8 日期和时间


  datatime 模块提供了处理日期和时间的一系列类,从简单到复杂.

>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2013, 3, 7)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'03-07-13. 07 Mar 2013 is a Thursday on the 07 day of March.'
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
17751



9 数据压缩


  常见的数据打包和压缩格式,在python中都得到直接支持,它们在下列模块中:zlib,gzip,bz2,zipfile和tarfile.

>>> import zlib
>>> str = "we repeat repeat and repeat many time"
>>> len(str)
37
>>> t = zlib.compress(str)
>>> len(t)
32
>>> zlib.decompress(t)
'we repeat repeat and repeat many time'



10 性能测量


  有些python用户需要比较解决同一问题时,不同方法的性能优劣.Python提供了相应的度量工具,可以快速得出结论.

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.05308699607849121
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.042800188064575195

  与timeit相比,profile和pstat模块提供了一系列工具,用于识别大段代码中的关键区域的时间.



11 质量控制


  开发高质量软件的一种方式是,在开发的过程为每一个函数编写测试程序,并多次运行它们. doctest 模块提供了一个工具,用于扫描一个模块,验证嵌入在程序 docstring 中的测试. 嵌入的测试代码结构非常简单,就像把输出的结果复制粘贴到测试代码后一样.

def average(values):
""" Computes the arithmetic mean of a list of numbers.
    >>> print average()
    40.0
    """
return sum(values, 0,0) / len(values+1)
import doctest
doctest.testmod()

  unittest 模块可不像 doctest 模块那样看起来不费吹灰之力,但是它可以写在独立的文件中, 用于更加复杂的测试.

import unittest
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average(), 40.0)
self.assertEqual(round(average(), 1), 4.3)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests




原文链接:http://docs.python.org/2/tutorial/stdlib.html
页: [1]
查看完整版本: 「学习笔记——Python」Python标准库简明教程