文件内容的批量查找,wxPython[适合于win,linux]+编码问题

来源:互联网 发布:java开根号 编辑:程序博客网 时间:2024/05/22 15:29
#! /usr/bin/env python# -*- coding: utf-8 -*-import wx,osfrom platform import system,refrom win32api import ShellExecuteout=NonerecordsCount=0suffixname="py"mPattern=""rr=Nonedef listDir(path,isRecursive=0):    global out,recordsCount,suffixname,mPattern,rr    if os.path.isfile(path):        li=[path]    else:        li=os.listdir(path)        #   print li    for l in li:        l = os.path.join(path, l)#传递绝对目录        if os.path.isdir(l):            if isRecursive==1:                listDir(l,isRecursive);            continue;        if suffixname!='*'and l[(l.rfind('.')+1):]!=suffixname:            continue            # print l        os.getcwd()        f=open(l)        cnt=0;        lineno=1        try:            for p in f.readlines():                flag=0                if rr is  None:                    flag=(p.decode('gbk').find(mPattern)>=0)                elif len(rr.findall(p.decode('gbk')))>0:                    flag=1                if flag:#将读出来的内容由gbk解码成utf-8                    if cnt==0:                    #      print "[",l,"]"                        out.write("[ %s ]\n" % l.encode('gbk'))#对文件名进行编码再写入进去--因为windows下文件内容编码是gbk                    cnt=cnt+1                    #   print lineno ,":", p.decode('gbk')#环境是utf8,读出的是gbk                    out.write("%d:%s\n" % (lineno,p))                lineno=lineno+1        except Exception,e:            print e        finally:            f.close()        recordsCount=recordsCount+cnt;class MyFrame(wx.Frame):    def __init__(self, *args, **kwds):        # begin wxGlade: MyFrame.__init__        kwds["style"] = wx.DEFAULT_FRAME_STYLE        wx.Frame.__init__(self, *args, **kwds)        self.text_ctrl_1 = wx.TextCtrl(self, -1, u"关键字/正则式")        self.check_0 = wx.CheckBox(self,-1,u"关键字?")        self.check_0.SetValue(True)        self.text_ctrl_2 = wx.TextCtrl(self, -1, u"文件后缀(txt)或*")        self.text_ctrl_3 = wx.TextCtrl(self, -1, u"输入路径")        self.button_1 = wx.Button(self, -1, u"目录定位")        self.check_1=wx.CheckBox(self,-1,u"递归查询")        self.check_1.SetValue(True)        self.__set_properties()        self.__do_layout()        # end wxGlade    def __set_properties(self):        # begin wxGlade: MyFrame.__set_properties        self.SetTitle(u"文件内容批量查找")        self.button_1.SetBackgroundColour(wx.Colour(5, 255, 60))        # end wxGlade    def __do_layout(self):        # begin wxGlade: MyFrame.__do_layout        sizer_1 = wx.BoxSizer(wx.VERTICAL)        grid_sizer_1 = wx.GridSizer(2, 3, 0, 0)        grid_sizer_1.Add(self.text_ctrl_1, 0, wx.EXPAND, 0)        grid_sizer_1.Add(self.text_ctrl_3, 1, wx.EXPAND, 0)        grid_sizer_1.Add(self.text_ctrl_2, 2, wx.EXPAND, 0)        grid_sizer_1.Add(self.check_0,3,wx.EXPAND,0)        grid_sizer_1.Add(self.check_1,4,wx.EXPAND,0)        grid_sizer_1.Add(self.button_1, 0, 0, 0)        sizer_1.Add(grid_sizer_1, 1, wx.EXPAND, 0)        self.text_ctrl_1.Bind(wx.EVT_TEXT_ENTER,self.OnClick1)        self.text_ctrl_2.Bind(wx.EVT_TEXT_ENTER,self.OnClick1)        self.text_ctrl_3.Bind(wx.EVT_TEXT_ENTER,self.OnClick1)        self.button_1.Bind(wx.EVT_LEFT_DOWN,self.OnClick1)        self.SetSizer(sizer_1)        sizer_1.Fit(self)        self.Layout()        # end wxGlade    def OnClick1(self,event):        if self.text_ctrl_1.Value==u"关键字/正则式":            msgdlg=wx.MessageDialog(None,u"请先输入关键字/正则式",u"@_@",wx.ICON_QUESTION)            msgdlg.ShowModal()            msgdlg.Destroy()            return        if self.text_ctrl_2.Value==u"文件后缀(txt)或*":            msgdlg=wx.MessageDialog(None,u"请先输入文件后缀",u"@_@",wx.ICON_QUESTION)            msgdlg.ShowModal()            msgdlg.Destroy()            return        path=''        if self.text_ctrl_3.Value==u'输入路径' or self.text_ctrl_3.Value=='':            dlg=wx.DirDialog(None,u"目录定位",os.getcwd())            if dlg.ShowModal()==wx.ID_OK:                self.text_ctrl_3.Value=path=dlg.GetPath()                del dlg            else:                del dlg                return        else:            path=self.text_ctrl_3.Value        global out,recordsCount,suffixname,mPattern,rr        recordsCount=0        out=open("results.txt","w")        mPattern=self.text_ctrl_1.Value        suffixname=self.text_ctrl_2.Value        isRecursive=0        if self.check_1.IsChecked():            isRecursive=1        if not self.check_0.IsChecked():            rr=re.compile(mPattern)        try:             #wx.MessageDialog(None,u"%d"%isRecursive,u"文件路径",wx.YES_NO|wx.ICON_QUESTION).ShowModal()             listDir(path,isRecursive)             out.write(u"found %d records" % recordsCount)        except Exception,e:            print e,"dfasdfasdfasf"        finally:            out.close()            # wx.MessageDialog(None,u"%s"%dlg.GetPath(),u"文件路径",wx.YES_NO|wx.ICON_QUESTION).ShowModal()        rr=None        sysstr = system()        if(sysstr =="Windows"):            #下载地址:http://nchc.dl.sourceforge.net/project/pywin32/pywin32/Build%20214/pywin32-214.win32-py2.7.exe            ShellExecute(0, 'open', 'notepad.exe','results.txt','',1)        elif(sysstr == "Linux"):            os.popen(r"gedit results.txt")# end of class MyFrameif __name__ == "__main__":    app = wx.PySimpleApp(0)    wx.InitAllImageHandlers()    frame_1 = MyFrame(None, -1, "")    app.SetTopWindow(frame_1)    frame_1.Show()    app.MainLoop()