python 等到连接激活

标签 python urllib

我希望我的 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()

最佳答案

绝对不要递归地做。改用循环:

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()

关于python 等到连接激活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10609358/

相关文章:

python - 将类从 linux 迁移到 windows 的问题 - Urllib.request

python - urllib 下载在线目录的内容

python - 朴素贝叶斯概率始终为 1

python - pandas 将 mysql utf-8 转换为 ascii

python - 用python实现 "Simplest Protocol"伪代码算法

python - 在每个循环中酸洗和加载 pandas 数据框以保存进度……坏主意?

python - 加快 urllib.urlretrieve

python - 使用lxml提取属性值

python - 我怎样才能从 url 中获取实时流?

javascript - 我可以在Python中找到javascript的结果吗?