# -*- coding:utf-8 -*- #!/usr/bin/env python # @Author : tianbao # @Contact : gmu1592618@gmail.com # @Time : 2018/4/5 17:06 # @File : change_host_file.py # @Software: PyCharm ''' 使用说明: PATH :HOSTS文件路径 NEW_PATH :新HOSTS文件路径 在change_host_file.py所在目录打开cmd运行以下命令 方法 IP 网址 添加:python change_host_file.py add 8.8.8.8 www.google.com 删除:python hange_host_file.py del 126.125.66.198 删除整行 修改:python hange_host_file.py change www.cnblogs.com www.google.com old new ''' import sys,os # 实际使用时,需要HOSTS文件正确路径,以下只为测试路径 PATH = 'G:\jiaoben\HOSTS' NEW_PATH = 'G:\jiaoben\HOSTS_NEW' def run(): try: if sys.argv[1] == 'add': with open(PATH,'a+',encoding='utf-8') as f: new_IP = sys.argv[2] + ' '+ sys.argv[3] f.write('\n') f.write(new_IP) sys.exit('添加成功,请查看源文件') elif sys.argv[1] == 'del': with open(PATH, 'r+', encoding='utf-8') as f,open(NEW_PATH, 'a+', encoding='utf-8') as f2: data = f.readlines() for line in data: if sys.argv[2] in line: continue f2.write(line) os.remove(PATH) os.rename(NEW_PATH,PATH) sys.exit('删除成功,请查看源文件') elif sys.argv[1] == 'change': with open(PATH, 'r+', encoding='utf-8') as f,open(NEW_PATH, 'a+', encoding='utf-8') as f2: for line in f.readlines(): if sys.argv[2] in line: line = line.replace('%s'%sys.argv[2],'%s'%sys.argv[3]) f2.write(line) os.remove(PATH) os.rename(NEW_PATH,PATH) sys.exit('修改成功,请查看源文件') except Exception as e: print(e) if __name__ == '__main__': run()