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程序内存泄漏调试的记录

问题描述 调试python程序时,用下面这段代码,可以获得进程占用系统内存值。程序跑一段时间后,就能画出进程对内存的占用情况。 def memory_usage_psutil():...

Python定时器实例代码

在实际应用中,我们经常需要使用定时器去触发一些事件。Python中通过线程实现定时器timer,其使用非常简单。看示例: import threading def fun_timer...

python3实现点餐系统

本文实例为大家分享了python3实现点餐系统的具体代码,供大家参考,具体内容如下 题目:     某餐厅外卖每天更新菜品,但是搭配价格是不变的,具体如下: &nbs...

Python操作Sql Server 2008数据库的方法详解

Python操作Sql Server 2008数据库的方法详解

本文实例讲述了Python操作Sql Server 2008数据库的方法。分享给大家供大家参考,具体如下: 最近由于公司的一个项目需要,需要使用Sql Server 2008数据库,开发...

python使用插值法画出平滑曲线

本文实例为大家分享了python使用插值法画出平滑曲线的具体代码,供大家参考,具体内容如下 实现所需的库 numpy、scipy、matplotlib 实现所需的方法 插值 nea...