python切换hosts文件代码示例

yipeiwu_com6年前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常见字符串操作函数小结【split()、join()、strip()】

本文实例讲述了Python常见字符串操作函数。分享给大家供大家参考,具体如下: str.split(' ') 1.按某一个字符分割,如‘.' >>> s = ('w...

python opencv实现旋转矩形框裁减功能

python opencv实现旋转矩形框裁减功能

本文实例为大家分享了python opencv实现旋转矩形框裁减的具体代码,供大家参考,具体内容如下 经常遇见旋转矩形框的裁减问题,那么思路是,将矩形框旋转正然后再裁减 # -*-...

python DataFrame 修改列的顺序实例

假设我有一个DataFrame(df)如下: name age id mike 10 1 tony 14 2 lee 20 3 现在我想把id 放到最前面,变成: id nam...

Python3.x和Python2.x的区别介绍

1.性能Py3.0运行 pystone benchmark的速度比Py2.5慢30%。Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可以取得很好的优化结果。Py3.1性能...

pandas中遍历dataframe的每一个元素的实现

假如有一个需求场景需要遍历一个csv或excel中的每一个元素,判断这个元素是否含有某个关键字 那么可以用python的pandas库来实现。 方法一: pandas的dataframe...