《可爱的python》中的第一个CDays小程序

这是在《可爱的python》中的第一个小程序CDays。也是一边看着书,一边写的,不过还没有添加图形界面,写着写着就有些犯懒啦。一共是两个文件,pycdc1.py和cdctools.py。运行的时候在ubuntu下敲入

python pycdc1.py

就OK了。由于自己写的,可能会有很多bug哦。github地址为:

git@github.com:cloudaice/CDays.git

下面贴上代码:

 1 #pycdc1.py
2
3 # -*- coding: utf-8 -*-
4 import sys
5 import cmd
6 from cdctools import *
7 class PYCDC(cmd.Cmd):
8 def __init__(self):
9 cmd.Cmd.__init__(self)
10 self.CDROM='/media/cdrom0'
11 self.CDDIR='cdc/'
12 self.prompt='(pycdc)>'
13 self.intro='''PYCDC0.5使用说明:
14 dir 目录名 指定保存目录或者搜索目录 默认是'cdc/'
15 walk 文件名 使用"*.cdc" 将扫描得到的目录放到该文件夹中
16 find 关键字 搜索遍历目录中的.cdc文件输出含有关键字的行
17 diskdir 目录名 指定要扫描的路径名和光盘名 默认是"/media/cdrom0"
18 ? 查询帮助
19 exit 退出系统
20 '''
21
22
23 def help_exit(self):
24 print '退出程序 quits the program'
25
26 def do_exit(self,line):
27 sys.exit()
28
29
30 def help_diskdir(self):
31 print "指定要扫描的光盘路径名以及光盘名"
32
33 def do_diskdir(self,diskdir):
34 if diskdir=='':
35 diskdir=raw_input("输入路径名及光盘名\n")
36 print "您输入的光盘名及路径名是 %s" % diskdir
37 self.CDROM=diskdir
38
39
40 def help_walk(self):
41 print "扫描光盘内容 walk cd and export into *.cdc"
42
43 def do_walk(self,filename):
44 if filename=="":
45 filename= raw_input("输入文件名:cdc:: ")
46 print "扫描光盘内容保存到:'%s'" % filename
47 cdwalker(self.CDROM,self.CDDIR+filename)
48
49
50 def help_dir(self):
51 print "指定保存/搜索目录"
52
53 def do_dir(self,pathname):
54 if pathname=="":
55 pathname=raw_input("输入指定保存/搜索目录:")
56 print "指定保存搜索目录是 ‘%s';默认是:'%s'" % (pathname,self.CDDIR)
57 self.CDDIR=pathname
58
59
60 def help_find(self):
61 print "搜索关键字"
62
63 def do_find(self,keyword):
64 if keyword=="":
65 keyword=raw_input("输入搜索关键字:")
66 print "搜索关键词: '%s'" % keyword
67 cdcgrep(self.CDDIR,keyword)
68
69 do_q=do_exit
70
71
72 if __name__== '__main__':
73 cdc=PYCDC()
74 cdc.cmdloop()
 1 #cdctools.py
2 # -*- coding:utf-8 -*-
3 import os
4 import sys
5 import chardet
6 def cdwalker(cdrom,cdfile):
7 export=""
8 for root,dirs,files in os.walk(cdrom):
9 export+=formatinfo(root,dirs,files)
10 open(cdfile,"w").write(export)
11
12 def cdcgrep(filepath,keyword):
13 filelist=os.listdir(filepath)
14 for cdc in filelist:
15 if '.cdc' in cdc:
16 cdcfile=open(filepath+cdc)
17 for line in cdcfile.readlines():
18 if keyword in line:
19 print line
20
21 def _smartcode(stream):
22 """smart stream into utf-8"""
23 codedetect = chardet.detect(stream)["encoding"]
24 ustring = unicode(stream,codedetect)
25 return ustring.encode('utf-8')
26
27 def formatinfo(root,dirs,files):
28 export = "\n"+root+"\n"
29 for d in dirs:
30 export+="-d %s %s \n" % (root,_smartcode(d))
31 for f in files:
32 export+="-f %s %s \n" % (root,_smartcode(f))
33 export+= "="*100
34 return export
35
36 if __name__ == '__main__':
37 cdwalker("/media/cdrom0",'s.cdc')