1. 1. 数据对象持久化  
2. 在某些时候,需要将数据对象的内容保存下来,方便下次程序启动时读取,这个就需要将对象持久化,请看如下例子   
3.  
4.   import pickle  
5.     
6.   # create the test dictionary  
7.   before_d = {}  
8.   before_d[1]="Name 1" 
9.   before_d[2]="Name 2" 
10.   before_d[3]="Name 3" 
11.     
12.   # pickle dump the dictionary  
13.   fout = open("dict1.dat", "w")  
14.   pickle.dump(before_d, fout, protocol=0)  
15.   fout.close()  
16.     
17.   # pickle load the dictionary  
18.   fin = open("dict1.dat", "r")  
19.   after_d = pickle.load(fin)  
20.   fin.close()  
21.     
22.   print( before_d )  # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}  
23.   print( after_d )   # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}  
24. 可以看出,我们将数据对象内容以文件的方式保存,可以作一些简单的cache处理,尤其是在写一些比较小的程序时,非常有用   
25.  
26. 2. 正则表达式替换  
27. 目标: 将字符串line中的 overview.gif 替换成其他字符串   
28.  
29.   >>> line = '<IMG ALIGN="middle" SRC="overview.gif" BORDER="0" ALT="">' 
30.   >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)  
31.     
32.   >>> mo.sub(r'"\1****"',line)  
33.   '<IMG ALIGN="middle" SRC="cdn_overview.gif****" BORDER="0" ALT="">' 
34.     
35.   >>> mo.sub(r'replace_str_\1',line)  
36.   '<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">'< /span> 
37.     
38.   >>> mo.sub(r'"testetstset"',line)  
39.   '<IMG ALIGN="middle" SRC="testetstset" BORDER="0" ALT="">' 
40. 注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用   
41.  
42. 3. 遍历目录方法  
43. 在某些时候,我们需要遍历某个目录找出特定的文件列表,可以通过os.walk方法来遍历,非常方便   
44.  
45.   import os  
46.   fileList = []  
47.   rootdir = "/tmp" 
48.   for root, subFolders, files in os.walk(rootdir):  
49.       if '.svn' in subFolders: subFolders.remove('.svn')  # 排除特定目录  
50.       for file in files:  
51.           if file.find(".t2t") != -1:                       # 查找特定扩展名的文件  
52.               file_dir_path = os.path.join(root,file)  
53.               fileList.append(file_dir_path)  
54.     
55.   print fileList  
56.  
57. 4. 列表按列排序(list sort)  
58. 如果列表的每个元素都是一个元组(tuple),我们要根据元组的某列来排序的化,可参考如下方法   
59.  
60. 下面例子我们是根据元组的第2列和第3列数据来排序的,而且是倒序(reverse=True)   
61.  
62.   >>> a = [('2011-03-17', '2.26', 6429600, '0.0'), ('2011-03-16', '2.26', 12036900, '-3.0'), ('2011-03-15', '2.33', 15615500,'-19.1')]  
63.   >>> print a[0][0]  
64.   2011-03-17 
65.   >>> b = sorted(a, key=lambda result: result[1],reverse=True)  
66.   >>> print b  
67.   [('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-17', '2.26', 6429600, '0.0'), ('2011-03-16', '2.26', 12036900, '-3.0')]  
68.   >>> c = sorted(a, key=lambda result: result[2],reverse=True)  
69.   >>> print c  
70.   [('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-16', '2.26', 12036900, '-3.0'), ('2011-03-17', '2.26', 6429600, '0.0')]  
71.  
72. 5. 列表去重(list uniq)  
73. 有时候需要将list中重复的元素删除,就要使用如下方法   
74.  
75.   >>> lst= [(1,'sss'),(2,'fsdf'),(1,'sss'),(3,'fd')]  
76.   >>> set(lst)  
77.   set([(2, 'fsdf'), (3, 'fd'), (1, 'sss')])  
78.   >>>  
79.   >>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]  
80.   >>> set(lst)  
81.   set([1, 3, 4, 5, 6, 7])  
82.     
83.  
84. 6. 字典排序(dict sort)  
85. 一般来说,我们都是根据字典的key来进行排序,但是我们如果想根据字典的value值来排序,就使用如下方法   
86.  
87.   >>> from operator import itemgetter  
88.   >>> aa = {"a":"1","sss":"2","ffdf":'5',"ffff2":'3'}  
89.   >>> sort_aa = sorted(aa.items(),key=itemgetter(1))  
90.   >>> sort_aa  
91.   [('a', '1'), ('sss', '2'), ('ffff2', '3'), ('ffdf', '5')]  
92. 从上面的运行结果看到,按照字典的value值进行排序的   
93.  
94. 7. 字典,列表,字符串互转  
95. 以下是生成数据库连接字符串,从字典转换到字符串   
96.  
97.   >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}  
98.   >>> ["%s=%s" % (k, v) for k, v in params.items()]  
99.   ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']  
100.   >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])  
101.   'server=mpilgrim;uid=sa;database=master;pwd=secret' 
102.  
103. 下面的例子 是将字符串转化为字典   
104.  
105.   >>> a = 'server=mpilgrim;uid=sa;database=master;pwd=secret' 
106.   >>> aa = {}  
107.   >>> for i in a.split(';'):aa[i.split('=',1)[0]] = i.split('=',1)[1]  
108.   ...   
109.   >>> aa  
110.   {'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'}  
111.  
112. 8. 时间对象操作  
113. 将时间对象转换成字符串   >>> import datetime  
114.   >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")  
115.   '2011-01-20 14:05' 
116.  
117. 时间大小比较   >>> import time  
118.   >>> t1 = time.strptime('2011-01-20 14:05',"%Y-%m-%d %H:%M")  
119.   >>> t2 = time.strptime('2011-01-20 16:05',"%Y-%m-%d %H:%M")  
120.   >>> t1 > t2  
121.   False 
122.   >>> t1 < t2  
123.   True 
124.  
125. 时间差值计算,计算8小时前的时间   >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")  
126.   '2011-01-20 15:02' 
127.   >>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M")  
128.   '2011-01-20 07:03' 
129.  
130. 将字符串转换成时间对象   >>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d")  
131.   >>> type(endtime)  
132.   <type 'datetime.datetime'>  
133.   >>> print endtime  
134.   2010-07-01 00:00:00 
135.   >>>   
136.  
137. 将从 1970-01-01 00:00:00 UTC 到现在的秒数,格式化输出   
138.  
139.   >>> import time  
140.   >>> a = 1302153828 
141.   >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a))  
142.   '2011-04-07 13:23:48' 
143. 9. 命令行参数解析(getopt)  
144. 通常在编写一些日运维脚本时,需要根据不同的条件,输入不同的命令行选项来实现不同的功能  
145. 在Python中提供了getopt模块很好的实现了命令行参数的解析,下面距离说明。请看如下程序:   
146.  
147.   #!/usr/bin/env python  
148.   # -*- coding: utf-8 -*-  
149.   import sys,os,getopt  
150.   def usage():  
151.       print ''''' 
152.   Usage: analyse_stock.py [options...] 
153.   Options:  
154.       -e : Exchange Name  
155.       -c : User-Defined Category Name 
156.       -f : Read stock info from file and save to db 
157.       -d : delete from db by stock code 
158.       -n : stock name 
159.       -s : stock code 
160.       -h : this help info 
161.       test.py -s haha -n "HA Ha"  
162.       ''' 
163.     
164.   try:  
165.       opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:')  
166.   except getopt.GetoptError:  
167.       usage()  
168.       sys.exit()  
169.   if len(opts) == 0:  
170.       usage()  
171.       sys.exit()  
172.     
173.   for opt, arg in opts:   
174.       if opt in ('-h', '--help'):  
175.           usage()  
176.           sys.exit()  
177.       elif opt == '-d':  
178.           print "del stock %s" % arg  
179.       elif opt == '-f':  
180.           print "read file %s" % arg  
181.       elif opt == '-c':  
182.           print "user-defined %s " % arg  
183.       elif opt == '-e':  
184.           print "Exchange Name %s" % arg  
185.       elif opt == '-s':  
186.           print "Stock code %s" % arg  
187.       elif opt == '-n':  
188.           print "Stock name %s" % arg  
189.     
190.   sys.exit()  
191.  
192. 注意: 这里我们使用短格式分析串"he:c:f:d:n:s:", 当一个选项只是表示开关状态时,即后面不带附加参数时,在分析串中写入选项字符。  
193. 当选项后面是带一个附加参数时,在分析串中写入选项字符同时后面加一个":"号  
194. 所以"he:c:f:d:n:s:" 就表示"h"是一个开关选项;"e:c:f:d:n:s:"则表示这些选项后面应该带一个参数.   
195.  
196. 10. print 格式化输出  
197. 10.1. 格式化输出字符串  
198. 截取字符串输出,下面例子将只输出字符串的前3个字母   >>> str="abcdefg" 
199.   >>> print "%.3s" % str  
200.   abc  
201. 按固定宽度输出,不足使用空格补全,下面例子输出宽度为10   >>> str="abcdefg" 
202.   >>> print "%10s" % str  
203.      abcdefg  
204. 截取字符串,按照固定宽度输出   >>> str="abcdefg" 
205.   >>> print "%10.3s" % str  
206.          abc  
207. 浮点类型数据位数保留   >>> import fpformat  
208.   >>> a= 0.0030000000005 
209.   >>> b=fpformat.fix(a,6)  
210.   >>> print b  
211.   0.003000 
212. 对浮点数四舍五入,主要使用到round函数   >>> from decimal import *  
213.   >>> a ="2.26" 
214.   >>> b ="2.29" 
215.   >>> c = Decimal(a) - Decimal(b)  
216.   >>> print c  
217.   -0.03 
218.   >>> c / Decimal(a) * 100 
219.   Decimal('-1.327433628318584070796460177')  
220.   >>> Decimal(str(round(c / Decimal(a) * 100, 2)))  
221.   Decimal('-1.33')  
222.   >>>   
223. 10.2. 进制转换  
224. 有些时候需要作不同进制转换,可以参考下面的例子(%x 十六进制,%d 十进制,%o 十进制)   
225.  
226.   >>> num = 10 
227.   >>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num)  
228.   Hex = a,Dec = 10,Oct = 12 
229.  
230. 11. Python调用系统命令或者脚本  
231. 使用 os.system() 调用系统命令 , 程序中无法获得到输出和返回值   >>> import os  
232.   >>> os.system('ls -l /proc/cpuinfo')  
233.   >>> os.system("ls -l /proc/cpuinfo")  
234.   -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo  
235.   0 
236.  
237. 使用 os.popen() 调用系统命令, 程序中可以获得命令输出,但是不能得到执行的返回值   >>> out = os.popen("ls -l /proc/cpuinfo")  
238.   >>> print out.read()  
239.   -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo  
240.     
241.   >>>  
242.  
243. 使用 commands.getstatusoutput() 调用系统命令, 程序中可以获得命令输出和执行的返回值   >>> import commands  
244.   >>> commands.getstatusoutput('ls /bin/ls')  
245.   (0, '/bin/ls')  
246.   >>>   
247. 12. Python 捕获用户 Ctrl+C ,Ctrl+D 事件  
248. 有些时候,需要在程序中捕获用户键盘事件,比如ctrl+c退出,这样可以更好的安全退出程序   
249.  
250.   try:   
251.       do_some_func()  
252.   except KeyboardInterrupt:  
253.       print "User Press Ctrl+C,Exit" 
254.   except EOFError:  
255.       print "User Press Ctrl+D,Exit" 
256.  
257. 13. Python 读写文件  
258. 一次性读入文件到列表,速度较快,适用文件比较小的情况下   track_file = "track_stock.conf"   
259.   fd = open(track_file)  
260.   content_list = fd.readlines()  
261.   fd.close()  
262.     
263.   for line in content_list:  
264.       print line  
265.  
266. 逐行读入,速度较慢,适用没有足够内存读取整个文件(文件太大)   fd = open(file_path)  
267.   fd.seek(0)  
268.   title = fd.readline()  
269.   keyword = fd.readline()  
270.   uuid = fd.readline()  
271.   fd.close()  
272.  
273. 写文件 write 与 writelines 的区别   
274. Fd.write(str) : 把str写到文件中,write()并不会在str后加上一个换行符   
275. Fd.writelines(content) : 把content的内容全部写到文件中,原样写入,不会在每行后面加上任何东西


http://blog.51cto.com/wangwei007/1102836