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 字符串、列表、元组的截取与切片操作示例

本文实例讲述了Python 字符串、列表、元组的截取与切片操作。分享给大家供大家参考,具体如下: demo.py(字符串、列表、元组的截取): # 切片(截取) [开始索引:结束索引...

Python使用reportlab将目录下所有的文本文件打印成pdf的方法

本文实例讲述了Python使用reportlab将目录下所有的文本文件打印成pdf的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf8 -*- #...

Pycharm之快速定位到某行快捷键的方法

Pycharm之快速定位到某行快捷键的方法

如下所示: 找了好久,今天无意中敲出来了:ctrl+l(小写) 全局查找某个变量:ctrl+h 我用的Eclipse快捷键 以上这篇Pycharm之快速定位到某行快捷键的方法就是小编分...

python并发和异步编程实例

关于并发、并行、同步阻塞、异步非阻塞、线程、进程、协程等这些概念,单纯通过文字恐怕很难有比较深刻的理解,本文就通过代码一步步实现这些并发和异步编程,并进行比较。解释器方面本文选择pyth...

使用PDB简单调试Python程序简明指南

使用PDB简单调试Python程序简明指南

在 Python 中也可以像 gcc/gdb 那样调试程序,只要在运行 Python 程序时引入 pdb 模块(假设要调试的程序名为 d.py): 复制代码 代码如下: $ vi d.p...