반응형
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
반응형
'Nice programing' 카테고리의 다른 글
새로운 Django 메시지 프레임 워크의 메시지에 HTML을 어떻게 출력합니까? (0) | 2020.11.27 |
---|---|
핵심 데이터를 미리 채우는 방법이 있습니까? (0) | 2020.11.27 |
Rails : Partials는 인스턴스 변수를 인식해야합니까? (0) | 2020.11.26 |
iPhone의 StatusBar에보기 추가 (0) | 2020.11.26 |
Linux에서 홈 디렉토리 가져 오기 (0) | 2020.11.26 |