Nice programing

urllib2의 시간 초과 처리?

nicepro 2020. 11. 27. 21:22
반응형

urllib2의 시간 초과 처리? -파이썬


urllib2의 urlopen 내에서 시간 초과 매개 변수를 사용하고 있습니다.

urllib2.urlopen('http://www.example.org', timeout=1)

시간 초과가 만료되면 사용자 지정 오류가 발생해야한다고 Python에 알리려면 어떻게해야합니까?


어떤 아이디어?


사용하려는 경우가 거의 없습니다 except:. 이렇게하면 디버그하기 어려울 수있는 모든 예외가 캡처 SystemExit되고 KeyboardInterupt프로그램을 사용하기가 귀찮게 만들 수있는 및를 포함한 예외가 캡처 됩니다.

가장 간단한 방법은 다음과 urllib2.URLError같습니다.

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

다음은 연결 시간이 초과 될 때 발생하는 특정 오류를 캡처해야합니다.

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

Python 2.7.3에서 :

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

참고 URL : https://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python

반응형