2012-01-06 47 views
8

Trước hết, sự cố của tôi khá giống với this one. Tôi muốn một thời gian chờ của urllib.urlopen() để tạo ra một ngoại lệ mà tôi có thể xử lý.Làm thế nào để xử lý thời gian chờ của urllib trong Python 3?

Điều này không thuộc URLError?

try: 
    response = urllib.request.urlopen(url, timeout=10).read().decode('utf-8') 
except (HTTPError, URLError) as error: 
    logging.error(
     'Data of %s not retrieved because %s\nURL: %s', name, error, url) 
else: 
    logging.info('Access successful.') 

Các thông báo lỗi:.

resp = urllib.request.urlopen (req, timeout = 10) .read() giải mã ('utf-8')
File "/ usr /lib/python3.2/urllib/request.py ", dòng 138, trong urlopen
return opener.open (url, dữ liệu, thời gian chờ)
Tệp" /usr/lib/python3.2/urllib/request.py ", dòng 369, trong mở
phản hồi = self._open (req, dữ liệu)
Tệp" /usr/lib/python3.2/urllib/request.py ", dòng 387, trong _open
'_open', req)
Tệp" /usr/lib/python3.2/urllib/request.py ", dòng 347, trong _call_chain
result = func (* args)
file "/usr/lib/python3.2/urllib/request.py", dòng 1156, trong http_open
trở self.do_open (http.client.HTTPConnection , req)
file "/usr/lib/python3.2/urllib/request.py", dòng 1141, trong do_open
r = h.getresponse()
file "/usr/lib/python3.2/ http/client.py ", dòng 1046, trong getresponse
lại sponse.begin()
File "/usr/lib/python3.2/http/client.py", dòng 346, ở bắt đầu
phiên bản, tình trạng, nguyên nhân = self._read_status()
File "/ usr/lib/python3.2/http/client.py ", dòng 308, trong _read_status
dòng = str (self.fp.readline (_MAXLINE + 1)," iso-8859-1 ")
Tệp"/usr/lib/python3.2/socket.py", dòng 276, trong readinto
trở self._sock.recv_into (b)
socket.timeout: timed out

có một cha lớn nge từ Python 3 khi họ tổ chức lại các mô-đun urlliburllib2 thành urllib. Liệu có thể có sự thay đổi sau đó gây ra điều này?

+0

Cách dễ dàng để khám phá các loại ngoại lệ là 'ngoại trừ Ngoại lệ như e: print (type (e)) ' . Giả sử bạn có thể sao chép ngoại lệ của bạn, đó là. – polvoazul

Trả lời

18

Trường hợp ngoại lệ là thời gian chờ từ ổ cắm, vì vậy

from socket import timeout 
try: 
    response = urllib.request.urlopen(url, timeout=10).read().decode('utf-8') 
except (HTTPError, URLError) as error: 
    logging.error('Data of %s not retrieved because %s\nURL: %s', name, error, url) 
except timeout: 
    logging.error('socket timed out - URL %s', url) 
else: 
    logging.info('Access successful.') 

nên bắt ngoại lệ mới. Mặc dù tôi không chắc chắn nếu câu trả lời cho câu hỏi của bạn, vì tôi không chắc câu hỏi của bạn là gì ..

Các vấn đề liên quan