转载:Python 绝对简明手册 2

  1.2. 常用函数不完全手册

dir(模块) #来获取模块的函数/变量列表

help(模块/函数) #获取相关的帮助

模块:os

  • 与操作系统相关的函数

例:

import os

os.getcwd() #当前脚本的工作目录

os.chidr() #改变当前工作目录

模块:shutil

  • 目录和文件管理的接口

例:

import shutil

shutil.copyfile('data.txt','archive.txt')

shutil.move('/build/a.txt','b.txt')

模块:glob

生成文件列表,支持通配符

例:

import glob

>>>glob.glob('*.py')

['primes.py','random.py','quote.py']

模块:sys

提供命令行参数,错误输出重定向和脚本终止

例:

命令行参数

如执行python demo.py one,two,three后

import sys

print sys.argv

会输出

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

终止脚本

sys.exit()

错误输出重定向,可以在stdout被重定向时显示错误信息

>>>sys.stderr.write('Warning , log file not found starting a new one/n')

Warning , log file not found starting a new one

模块:re

字符正值表达式匹配

例:

import re

>>>re.findall(r'/bf[a-z]*','which foot or hand fell fastest')

['foot','fell','fastest']

>>>re.sub(r'(/b[a-z]+)/l',r'/l','cat in the hat')

'cat in the hat

模块:math

为浮点运算提供了底层C函数库的访问

例:

>>>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) #随机值不会重复

[20,42,12,44,57,88,93,80,75,56]

>>>random.random()

0.26676389968666669

>>> random.randrange(10)

7

模块:urblib2

打开url地址

例:

for line in urllib2.urlopen('http://www.python.org/')

  • print line

模块:smtplib

发送电子邮件

例:

sever=smtplib.smtp('localhost')

sever.sendmail('[email protected]','[email protected]')

"""TO:[email protected]

From:[email protected]

"""

sever.quit()

模块:datetime

时间日期相关算法以及格式化输出

例:

from datetime import date

now=date.today

>>>now

datetime.date(2006, 9, 13)

>>>now.strftime("%m-%d-%y . %d %b %Y is a %A on the %d day of %B . ")

'09-13-06 . 13 Sep 2006 is a Wednesday on the 13 day of September . '

birthday=date(1986,6,30)

age=now-birthday

>>> age.days

7380

模块:zipfile / tarfile

数据打包和压缩,支持格式:zlib,gzip,bz2,zipfile和tarfile

例:

import zlib

s="which which which which"

  • t=zlib.compress(s)

>>>len(s)

23

>>>len(t)

16

>>>zlib.decompress(t)

"which which which which"

>>>zilb.crc(32)

-487390043

模块:timeit

性能测试

例:

from timeit import Timer

#Timer的第一个参数是要测试时间的语句,第二个参数是初始化

#timeit的参数是测试语句的执行次数,默认执行1000000次

>>> Timer('t=a;a=b;b=t','a=1;b=2').timeit()

0.31399409701512582

>>> Timer('a,b=b,a','a=1;b=2').timeit()

0.247945758469313663

模块:profile和pstats提供了对更大代码块的测量工具

模块:doctest

质量测试,测试代码.

他将对函数文档中的测试代码进行测试,他使文档的撰写和软件的测试融合了起来

例:

def average(values):

  • """Computer average

#注意>>> 和测试代码之间要空一格,测试结果前面不要有空格

>>> print average([10,90,53])

51.0

  • """ return sum(values,0.0)/len(values)

import doctest

doctest.testmod()

模块:unittest

可以在一个独立的文件中提供一个更全面的代码测试.

例:

import unittest

class TestStatisticalFunctions(unittest.TestCase):

  • def test_average(self):
    • self.assertEqual(average([20,30,70]),40.0) self.assertEqual(round([1,5,7]),1) 
      self.assertRaises(ZeroDivisionError,average,[]) 
      self.assertRaises(TypeError,average,20,30,70)

unittest.main()

其他一些常用模块

xmlrpclib和SimpleXMLRPCServer可以在琐碎的任务中调用远程过程

email可以构建和解析复杂的消息结构,包括附件,文字编码和头协议等等

xml.dom和xml.sax

csv通用数据库中直接读写

gettext,locale,codecs国际化(i18n)支持

模块:pprint

美化打印(pretty printer)

例:

import pprint

t=[[ ['blue','cyan'] ,['green','red'],'yellow' ],'while']

>>> pprint.pprint(t,width=30)

[[['blue', 'cyan'],

  • ['green', 'red'], 'yellow'],
  • 'while']

模块:textwrap

格式化段落来适应行宽

例:

import textwrap

doc="""Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks()."""

>>> print textwrap.fill(doc,width=40)

Object for wrapping/filling text. The

public interface consists of the wrap()

and fill() methods; the other methods

are just there for subclasses to

override in order to tweak the default

behaviour. If you want to completely

replace the main wrapping algorithm,

you'll probably have to override

_wrap_chunks().

模块:locale

国际化

例:

import locale

locale.setlocale(locale.LC_ALL,'English_United States.1252')

x=1234567.8

>>>locale.format("%d",x,grouping=True)

'1,234,567'

conv=locale.localeconv()

>>> locale.format("%s%.*f",(conv['currency_symbol'],conv['frac_digits'],x),grouping=True)

'$1,234,567.80'

模块:string.template

生成句子的模版,输入"张沈鹏",生成"大家好,我的名字是张沈鹏."

例:

from string import Template

t=Template('${village}flok send $$10 to $cause')

t.substitute(village='Nottingham',cause='the ditch fund')

'Nottinghamflok send $10 to the ditch fund'

当占位符没有提供时substitute会抛出KeyError的异常

而safe_substitute可以在占位符提供不完整时保留占位符,而不抛出异常

模块:struct

用于读取二进制格式的文件

例:#H 代表unsigned short , read(2)因为unsigned short占2个bytes

#L 代表4字节的无符号整数

data=open('myfile.zip','rb').read()

start=0

for i in xrange(3):

  • start+=14 fields=struct.unpack('LLLHH',data[start:start+16]) crc32,comp_size,uncompsize,filenamesize,extra_size=fields start+=16 filename=data[start:start+filenamesize] start+=filenamesize extra=data[start:start+extra_size] print filename,hex(crc32),comp_size,uncomp_size start+=extra_size+comp_size #下一个头文件

模块:threading

线程

例:

import threading,zipfile

class AsyncZip(threading.Thread)

  • def init(self , infile , outfile):
    • self.infile=infile self.outfile=outfile 
      def run(self):
    • f=zipfile.ZipFile(self.outfile , 'w' , zipfile.DEFLATED) f.write(self.infile) f.close() print 'Finished background zip of: ', self.infile

background=AsyncZip('mydata.txt','myarchive.zip')

background.start()

print 'The main program continues to run in foreground'

background.join() #Wait for the background task finish

print 'Main program waitwd until background was done .'

  • 模块:Queue 协多线程的资源调用

模块:logging

日志

例:

import logging

logging.debug('Debugging information')

logging.info('Information message')

logging.warning('Warning:coinfig file %s not found','server.conf')

logging.error('Error occurred')

logging.critical('Critical error -- shutting down')

输出:

WARNING:root:Warning:config file server.conf not found

ERROR:root:Error occurred

CRITICAL:root:Critical error -- shutting down

模块:wearef

不创建引用来跟踪对象

例:

>>>import weakref,gc

>>>class A :

...def init (self,value):

... self.value=value

...def repr(self):

... return str(self.value)

...

>>>a=A(10) #create a reference

>>>d=weakref.WeakValueDictionary()

>>>d['primary']=a #does not create a reference

>>>d['primary'] #fetch the object if it is still alive

10

>>>del a #remove the one reference

>>>gc.collect() #run garbage collection right away

0

>>>d['primary'] #entry was automatically removed

Traceback(mostrecentcalllast):

File "<pyshell#108>",line1,in-toplevel-

d['primary'] #entry was automatically removed

File "C:/PY24/lib/weakref.py" , line46 , in getitem

o = self.data[key]()

KeyError:'primary'

  • 模块:array 类似列表的对象,比默认的列表更紧凑,仅用来存储数据 例: from array import array

#存储双字节无符号整数,编码类型为H a=array('H',[4000,10,700,22222])

>>> sum(a)

26932

>>>a[1:3]

array('H',[10,700])

模块:collections

提供了类似列表的deque对象,它从左边添加(append)和弹出(pop)更快,但在内部查询更慢.适用于队列的实现和广度优先树的搜索

例:

from collection import deque

d=dequetask1","task2","task3

d.append("task4")

>>>print "Handling",d.popleft()

Handling task1

unsearched=deque([start_nodel])

def breadth_first_search(unsearched):

  • node=unsearch.popleaf() for m in gen_moves(node):
    • if is_goal(m):
      • return m 
        unsearched.append(m)

模块:bisect

操作存储列表

例:

import bisect

scores=[(100,'perl'),(200,'tcl'),(400,'lua'),(500,'python')]

bisect.insort(scores,(300,'ruby'))

>>>scores

[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

模块:heapq

提供基于正常列表的堆实现,最小总是第一个元素(0点),对希望循环访问最小元素但不想执行完整堆排列非常有用

例:

from heapq import heapify,heappop,heappush

data=[1,3,5,6,7,8,9,65,0]

heapify(data)

heappush(data,-5)

[heappop(data) for i in range(3) ]

>>> [heappop(data) for i in range(3) ]

[-5, 0, 1]

  • 模块:decimal

提供了一个Decimal数据类型,用于浮点数高精度的计算,高精度使Decimal可以执行二进制浮点数无法进行的模运算和等值测试

例:

from decimal import *

>>>Decimal('0.70')*Decimal('1.05'))

0.7350

>>> .70*1.05

0.73499999999999999

>>>sum([Decimal('0.1')*10==Decimal('1.0')])

True

>>>sum([0.1*10])==1.0

False

>>>Decimal('1.00')%Decimal('.10')

Decimal("0.00")

>>> 1.00%0.10

0.09999999999999995

getcontext().prec=36

>>>print Decimal(1)/Decimal(7)

0.142857142857142857142857142857142857

你可能感兴趣的:(python,测试,import,reference,methods,操作系统相关)