2012-05-15 62 views
3

我想让我的python脚本检查一个活动的互联网连接,如果有一个然后继续执行。如果没有连接,请继续检查。基本上阻止执行“main()”,直到脚本可以重新连接。python等到连接激活

蟒蛇

import urllib2 

def main(): 
    #the script stuff 

def internet_on(): 
    try: 
     response=urllib2.urlopen('http://74.125.113.99',timeout=1) 
     main() 
    except urllib2.URLError: 
    internet_on() 
+4

Stack Overflow是不是你个人的研究助理:http://meta.stackexchange.com/a/128553 –

+2

^^感谢您的评论... – Blainer

回答

4

绝对不这样做递归。使用一个循环,而不是:

def wait_for_internet_connection(): 
    while True: 
     try: 
      response = urllib2.urlopen('http://74.125.113.99',timeout=1) 
      return 
     except urllib2.URLError: 
      pass 

def main(): 
    ... 

wait_for_internet_connection() 
main()