测试修改hosts文件py小工具

import sys,os
parm_list=sys.argv
HOST_PATH=r'C:\liuliang\flask_test\test\hosts'
class HostFile(object):
def __init__(self,parm_list):
self.parm_list=parm_list
self.open_file()
if len(parm_list)==1:
self.get()
else:
method=parm_list[1]
if hasattr(self,method):
func=getattr(self,method)
func()
else:
print('输入格式有误')
self.close_file()

def open_file(self):
self.f=open(HOST_PATH,'r+',encoding='utf-8')
def close_file(self):
self.f.close()

def get(self):
for line in self.f:
print(line.strip())
def delete(self):
ip=self.parm_list[2]
new_f=open(r'C:\liuliang\flask_test\test\new_hosts','w',encoding='utf-8')
for line in self.f:
if ip in line:
continue
new_f.write(line)
new_f.close()
self.close_file()
os.remove(HOST_PATH)
os.rename(r'C:\liuliang\flask_test\test\new_hosts',r'C:\liuliang\flask_test\test\hosts')

def update(self):
ip = self.parm_list[2]
domain=self.parm_list[3]

new_f = open(r'C:\liuliang\flask_test\test\new_hosts', 'w', encoding='utf-8')
for line in self.f:
if ip in line or domain in line:

new_f.write('\n# %s %s\n' % (ip, domain))
continue

new_f.write(line)
new_f.close()
self.close_file()
os.remove(HOST_PATH)
os.rename(r'C:\liuliang\flask_test\test\new_hosts',r'C:\liuliang\flask_test\test\hosts')

def add(self):
ip=self.parm_list[2]
domain=self.parm_list[3]

self.f.seek(0,2)

self.f.write('\n# %s %s'%(ip,domain))

hostfile=HostFile(parm_list)
上一篇:JDBC(通俗易懂)简单的操作(增、删、改、查)


下一篇:TensorFlow tutorial