最近寢室網(wǎng)不太好,經(jīng)常莫名其妙的連不上網(wǎng)。害的我上次一個(gè)上午沒(méi)有收集到數(shù)據(jù)歧杏。其實(shí)也簡(jiǎn)單镰惦,每次手動(dòng)在自己寢室和隔壁寢室之間切換就可以了。犬绒。旺入。那我不在電腦旁邊的時(shí)候誰(shuí)來(lái)切?還是編個(gè)自動(dòng)切換wifi的程序吧:-) 以后迅雷下載的時(shí)候也有用呢:-)
為了便于在其他程序中調(diào)用凯力,這個(gè)程序被做成了模塊的形式眨业。
# 再一次感到了Python用來(lái)做開(kāi)發(fā)時(shí)的便利性,可以快速把想法付諸實(shí)施沮协。這次這個(gè)程序用了一個(gè)多小時(shí)就完成了~
# 借此機(jī)會(huì)練習(xí)了一下正則表達(dá)式龄捡,真是神器~ Python可以和CMD做聯(lián)合編程,就是說(shuō)以前學(xué)的CMD的技術(shù)也可以用上了慷暂,好爽~
調(diào)用方式:(放在同一個(gè)文件夾下)
importkol
kol.func()
為了隱私聘殖,wifi的SSID已經(jīng)隱去,請(qǐng)按需要修改行瑞。
配置文件的設(shè)置方式:
http://tech.diannaodian.com/security/wl/wx/2013/0227/228620.html
# Keep OnLine(wifi)
# Designed by Xc.Li
# Dec.2015
import urllib
import os
import re
import time
import winsound
def get_wifi():
#get the current name of wifi
#netsh wlan show interfaces
flag = 0 #whether connected to a wifi?
report = os.popen('netsh wlan show interfaces')
for line in report:
if re.search('^ *SSID',line):
current_wifi_name = re.findall('^.*: (.*)',line)[0]
flag = 1
if flag == 0:
current_wifi_name = 0
return current_wifi_name
def connect_wifi(wifi_name):
# netsh wlan add profile filename="E:\WLAN-call me daddy.xml"
# netsh wlan connect name="call me daddy" ssid="call me daddy" interface="WLAN"
if wifi_name == 0:
new_connection = '23-608'
if wifi_name == '23-608':
new_connection = 'call me daddy'
if wifi_name == 'call me daddy':
new_connection = '23-608'
os.system('netsh wlan add profile filename="D:\OneDrive\Python\material\WLAN-'+new_connection+'.xml"')
os.system('netsh wlan connect name="'+new_connection+'" ssid="'+new_connection+'" interface="WLAN"')
def func():
while (True):
try:
print 'Trying to connect Baidu...'
urllib.urlopen('http://www.baidu.com')
print 'Connection is OK!'
break
except:
print 'Fail to connect Baidu!'
print 'currently connected to:',get_wifi()
connect_wifi(get_wifi())
winsound.Beep(880,1000)
print 'wait...'
time.sleep(5) #it takes some time to establish a connection