python切换hosts文件代码示例

yipeiwu_com5年前Python基础

win7以上需要使用管理员权限操作。

复制代码 代码如下:

# -*- coding: utf-8 -*-
import os
import glob
import shutil

def format_file_list(files):
        all_files_str = ""
        for i in range(len(files)):
                all_files_str +=  str(i)+":"+files[i]+"\n"
        return all_files_str

hosts_path = "C:\\Windows\\System32\\drivers\\etc"
files =  os.listdir(hosts_path)
os.chdir(hosts_path)

if os.getcwd() != hosts_path:
        print("Switch Dir to System32 Error,check permission!\npwd:"+os.getcwd())
        exit()

hosts_files = glob.glob("host*")
choosed_file_idx = int(input("Choose Hosts File Index:\n"+format_file_list(hosts_files)))
files_num = len(hosts_files)

if (choosed_file_idx < 0 or choosed_file_idx >= files_num) :
        print("Please choose a file in the lists!")
        exit()

print("Choosed idx:{0},file:{1}.".format(choosed_file_idx,hosts_files[choosed_file_idx]))
shutil.copy("hosts","hosts.bak")
shutil.copy(hosts_files[choosed_file_idx],"hosts")
print("Copy ok,then flush dns...")
os.system("ipconfig /flushdns")

相关文章

Python语言快速上手学习方法

最近在学习Python,后面搞机器人项目需要用到,所以要快速上手,我使用的是PyCharm这个IDE,看起来就舒服,学习起来就有劲啦,作为一名有工作经验的老司机,我学习编程语言的方法不会...

详解Python之unittest单元测试代码

详解Python之unittest单元测试代码

前言 编写函数或者类时,还可以为其编写测试。通过测试,可确定代码面对各种输入都能够按要求的那样工作。 本次我将介绍如何使用Python模块unittest中的工具来测试代码。 测试函数...

python实现朴素贝叶斯分类器

本文用的是sciki-learn库的iris数据集进行测试。用的模型也是最简单的,就是用贝叶斯定理P(A|B) = P(B|A)*P(A)/P(B),计算每个类别在样本中概率(代码中是p...

python 接口实现 供第三方调用的例子

python 接口实现 供第三方调用的例子

实验环境 1.环境问题 python 2.7 以上自带的pyunit bottle 作为一个python的简易服务器 在python安装目录 打开命令窗口(具体 shift+鼠标右键)...

为什么从Python 3.6开始字典有序并效率更高

为什么从Python 3.6开始字典有序并效率更高

在Python 3.5(含)以前,字典是不能保证顺序的,键值对A先插入字典,键值对B后插入字典,但是当你打印字典的Keys列表时,你会发现B可能在A的前面。 但是从Python 3.6...