最近寝室网不太好,经常莫名其妙的连不上网。害的我上次一个上午没有收集到数据。其实也简单,每次手动在自己寝室和隔壁寝室之间切换就可以了。。。那我不在电脑旁边的时候谁来切?还是编个自动切换wifi的程序吧:-) 以后迅雷下载的时候也有用呢:-)
为了便于在其他程序中调用,这个程序被做成了模块的形式。
# 再一次感到了Python用来做开发时的便利性,可以快速把想法付诸实施。这次这个程序用了一个多小时就完成了~
# 借此机会练习了一下正则表达式,真是神器~ Python可以和CMD做联合编程,就是说以前学的CMD的技术也可以用上了,好爽~
调用方式:(放在同一个文件夹下)
importkol
kol.func()
为了隐私,wifi的SSID已经隐去,请按需要修改。
配置文件的设置方式:
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