Sample code for switching the hosts file in python

Source: Internet
Author: User
Tags glob
When developing or testing website programs, we often encounter switching back and forth between multiple hosts files. The windows hosts file directory is very deep and troublesome. therefore, you have written a script in python to simplify this function. you need to use the administrator privilege for operations above win7.

The code is as follows:


#-*-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 ")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.