如何在Python中捕获任何套接字错误?

时间:2014-10-19 15:54:53

标签: python sockets httplib

我正在尝试检查jpg的URL是否真实。此代码有效,如果jpg存在,则返回True

import httplib

def exists(site, path):

    conn = httplib.HTTPConnection(site)
    conn.request('HEAD', path)
    response = conn.getresponse()
    conn.close()
    return response.status == 200

print exists('uploads1.wikiart.org',
             '/images/vincent-van-gogh/vincent-s-bedroom-in-arles-1889.jpg')

但是,如果我将其发送到不存在的网址,例如'uploads1111.wikiart.org',,我会收到一个套接字错误:

socket.error: [Errno 10060] A connection attempt failed 
because the connected party did not properly respond after a period of time

我搜索了一个答案,发现与errno模块有关,但无法成功地将该代码应用到我自己的代码中。我正在尝试捕获任何套接字错误并返回False(如果有)。

1 个答案:

答案 0 :(得分:1)

回答我自己的问题:

import httplib
import socket


def exists(site, path):

    try:
        conn = httplib.HTTPConnection(site)
        conn.request('HEAD', path)
        response = conn.getresponse()
        conn.close()
        return response.status == 200

    except socket.error:
        return False