python改变系统hosts
因工作需要一直修改系统hosts,以切换内网,外网,其他测试服务器。
天天改比较麻烦写了这个小工具比较简单, 打包成EXE后比较大(不过自己用的东西就没啥讲究了)
贴上源代码
#-* coding:GBK *-
import os
import wx
def create(parent):
return Frame1(parent)
# assign ID numbers
[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1LISTBOX1,
] = [wx.NewId() for _init_ctrls in range(4)]
class Frame1(wx.Frame):
def _init_ctrls(self, prnt):
# BOA generated methods
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(400, 400), size=wx.Size(500, 400),
style=wx.DEFAULT_FRAME_STYLE, title='改系统hosts,需要把要修改的hosts文件放在hosts目录下面')
self.SetClientSize(wx.Size(750, 300))
self.listBox1 = wx.ListBox(choices=[], id=wxID_FRAME1LISTBOX1,
name='listBox1', parent=self, pos=wx.Point(10, 10),
size=wx.Size(200, 240), style=0)
self.t1 = wx.TextCtrl(self, -1,"",size=(520, 280), pos=wx.Point(220, 10),style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
'''列表目录中所有文件'''
for i in os.listdir('./hosts/'):
self.listBox1.Append(i)
self.listBox1.Bind(wx.EVT_LISTBOX, self.OnListBox1Listbox,
id=wxID_FRAME1LISTBOX1)
self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label='改写系统hosts',
name='button2', parent=self, pos=wx.Point(10, 260),
size=wx.Size(200, 30), style=0)
self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
id=wxID_FRAME1BUTTON2)
def __init__(self, parent):
self._init_ctrls(parent)
def OnListBox1Listbox(self, event):
selName = './hosts/' + self.listBox1.GetStringSelection()
#self.SetTitle(selName)
f = open(selName, "r+")
try:
all_the_text = f.read( )
finally:
f.close()
self.t1.Clear()
self.t1.write(all_the_text)
def OnButton2Button(self, event):
x = os.getenv('WINDIR')+"\system32\drivers\etc\hosts"
v = self.t1.GetValue();
v = v.encode('gb2312')
f = open(x, 'w')
f.writelines(v)
f.close( )
#--------------- end of class Frame1 --------------------
# program entry point ...
if __name__ == '__main__':
app = wx.PySimpleApp()
wx.InitAllImageHandlers()
frame = create(None)
frame.Show()
app.MainLoop()