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 读取视频,处理后,实时计算帧数fps的方法

实时计算每秒的帧数 cap = cv2.VideoCapture("DJI_0008.MOV") #cap = cv2.VideoCapture(0) # Define the...

Python实现统计给定字符串中重复模式最高子串功能示例

本文实例讲述了Python实现统计给定字符串中重复模式最高子串功能。分享给大家供大家参考,具体如下: 给定一个字符串,如何得到其中重复模式最高的子字符串,我采用的方法是使用滑窗机制,对给...

python获取当前计算机cpu数量的方法

本文实例讲述了python获取当前计算机cpu数量的方法。分享给大家供大家参考。具体分析如下: 这里实际上返回的是计算机的cpu核心数,比如cpu是双核的,则返回2,如果双四核cpu,则...

Python requests发送post请求的一些疑点

Python requests发送post请求的一些疑点

前言 在Python爬虫中,使用requests发送请求,访问指定网站,是常见的做法。一般是发送GET请求或者POST请求,对于GET请求没有什么好说的,而发送POST请求,有很多朋友不...

在Pycharm中对代码进行注释和缩进的方法详解

一、注释 1. #单行注释 2. """ 多行注释 """ 3. pycharm多行注释快捷键:Ctrl+/ 二、缩进 缩进:Tab 反向缩进:Shift+Tab 以上这篇在...