随机“[Errno -2] 名称或服务未知"错误 [英] Random "[Errno -2] Name or service not known" errors

查看:98
本文介绍了随机“[Errno -2] 名称或服务未知"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第三方服务填充本地数据库.我有一个网址列表(大约 500 个).我在循环中调用每个 url,并使用返回的数据更新我的数据库.代码流如下所示:

I am populating a local database using a third party service. I have a list of urls (around 500). I am calling each url in a loop, and updating my database with the returned data. The code flow looks like this:

for url in urllist:
    req = urllib.urlopen(url)
    data = json.loads(req.read())
    req.close()

    #update the db using data here

每当我运行这段代码时,脚本会随机失败并显示错误消息名称或服务未知".这与 url 没有任何关系,因为脚本在随机点失败(即在一次运行中的第 50 次迭代,以及在另一次运行中的第 60 次迭代)

Whenever I run this piece of code, the script fails at random points with the error message "Name or service not known". This doesn't have anything with the urls because the script fails at random points (i.e. at 50th iteration in one run, and at 60th iteration in another)

这可能是什么原因?

推荐答案

如果您使用了错误的代理或存在网络问题,您可以试试这个:

if you use a bad proxy or there are network problems you can try this:

for url in urllist:
    retry = 0
    while True: # retry request
        try:
            req = urllib.urlopen(url)
            resp_data = req.read() # in call read() network still processing
        except Exception as e: # TODO need more detailed handling
            if retry > 3: # 3 this is serious problem. exit
                raise e
            retry += 1 # retry
        else:
            data = json.loads()
            req.close() # not needed
            break

这篇关于随机“[Errno -2] 名称或服务未知"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆