今天新写了一个Tk程序,原因是单位的网络由网通换成电信的了,IP也改了,局域网的由原来的192.168.1.222换乘了192.168.0.222之类的。原来CVS服务器上的IP地址也不得不改了,这下可好,原先本地与服务器相对应的工程统统失效了,每次操作总指向原先的IP地址。除了该登录配置的IP地址之外,本地CVS目录下的Root文件里的IP地址也得修改。

      这种场合,Python自然有用武之地了。翻出原来写的一个Tk程序,改了几行,主要是删除垃圾代码,遍历指定目录下的所有Root文件,最后将Root文件里的IP地址替换成新的。其实不用写界面的话,脚本会更快一些,为了方便别人,我就改写了原先的Tk程序,源代码如下:


# -*- coding: cp936 -*-
from Tkinter import *
from tkMessageBox import *
#from FileDialog import *
from tkFileDialog import askopenfilename,askdirectory


from os.path import walk, join, normpath
import sys

class EntryDemo(Frame):
    """ Demonstrate Entrys and Envent Building"""

    def __init__(self,master):
        Frame.__init__(self)
        self.master = master
       
        self.pack(expand=YES,fill = BOTH)
        self.master.title("Replace Tool")
        self.master.geometry("280x80") #width X length

        self.array()
        self.files = []
        self.path = None
       
        self.loop = 0
        self.total = 0
        self.numFind = 0
        self.errors = 0       

    def array(self):
        #Entry Demo
        self.frame1 = Frame(self)
        self.frame1.pack( pady = 2 ) #垂直间距      

        #=========================================
        self.label3 = Label(self.frame1,
                            name = 'label3',
                            text = r'Project path (e.g.: E:\6223C_07B\ )')
        
        self.label3.grid(row = 5, column = 0)       

        self.text3 = Entry(self.frame1,
                           name="text3",
                           width = 30
                           )
        self.text3.grid(row = 6, column = 0)
       
        self.btnOpenPrj = Button(self.frame1,
                              name = 'btnOpenPrj',
                              text = 'Open',
                              relief = RAISED,
                              command = self.openProject
                              )
        self.btnOpenPrj.grid(row = 6, column = 1)      

        #button Demo
        self.rPrjBtn=Button(self.frame1,
                                text="Replace Project",
                                command= self.replacePrj)
        self.rPrjBtn.bind("<Enter>", self.rolloverEnter) #鼠标事件:进入
        self.rPrjBtn.bind("<Leave>", self.rolloverLeave) #鼠标事件:离开
        self.rPrjBtn.grid(row = 7, column = 0)


    def openProject(self):
        self.path = askdirectory()

        if self.path <> None:
            self.text3.delete(0,END)
            self.text3.insert(INSERT, self.path)

    def replacePrj(self):      
        self.path = self.text3.get()
        if self.path == '':
            showwarning("Info",'Plz fullfill the project path.')           
            return     

        self.files = []
        #get all the files in the path
        self.mywalk(self.path)

        self.loop = 0
        self.total = len(self.files)

#        print self.files
        self.numFind = 0
        self.errors = 0
        info = "%d files,processing..." % (self.total)
        self.master.title(info)
        for aFile in self.files:
            result = self.fileEncode(aFile)
            if result == 2:
                self.numFind += 1
                pass
            elif result == 1:
                pass
            else:
                errors += 1
                pass    
           
        info = "Total files: %d\nReplace files: %d\nErrors: %d" % (self.total,self.numFind,self.errors)
        showinfo("Finish",info)
        self.master.title("Replace Tool")
   
    def rolloverEnter(self,event):
        event.widget.config(relief=GROOVE)
       
    def rolloverLeave(self,event):
        event.widget.config(relief=RAISED)

    def visit(self, arg,dirname, names):
    #    files=[normpath(join(dirname, file)) for file in names]
        for file in names:
            if file[:] == 'Root':
                self.files.append(normpath(join(dirname, file)))

    def mywalk(self,path):
        self.master.title("Searching...")
        walk(path, self.visit, 0)          

    def fileEncode(self,sourceFile,key = None,bForce = False):
        self.loop += 1
        info = "Processing: %d/%d" % (self.loop,self.total)
        self.master.title(info)
       
        try:          
            fp = open(sourceFile,'r')
            lines = fp.readlines()
            fp.close()         
        except:
            return 0
           
        find = False
        bScope = False
        text = ""
      
        for line in lines:
            bScope = True
            text = line.replace('192.168.1.200','192.168.0.200')
            break
           
        if bScope:
            #rewrite the file
            try:
                fp2 = open(sourceFile,'w')
                fp2.write(text)
                fp2.close()             
            except:
                return 0
            return 2
        else:
            return 1
      

def about():
    showinfo("About",'CopyRight 2008: me: \nxdush-yy@yahoo.com.cn')

   
def main():
    root = Tk()

    menu = Menu(root)
    root.config(menu = menu)

    filemenu = Menu(menu)
    menu.add_cascade(label = "File", menu = filemenu)
    filemenu.add_command(label = "Exit", command = root.quit)

    helpmenu = Menu(menu)
    menu.add_cascade(label = "Help", menu = helpmenu)
    helpmenu.add_command(label = "About...", command = about)

    EntryDemo(root)
    root.mainloop()

if __name__=="__main__":
    main()