最近寢室網不太好,經常莫名其妙的連不上網。害的我上次一個上午沒有收集到數據。其實也簡單,每次手動在自己寢室和隔壁寢室之間切換就可以了。。。那我不在電腦旁邊的時候誰來切?還是編個自動切換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