Python - 如何捕获gevent套接字超时异常

时间:2014-05-20 20:04:38

标签: python sockets gevent

import gevent.monkey
gevent.monkey.patch_socket()
import requests
from gevent.pool import Pool
import socket

urls = ["http://www.iraniansingles.com"]


def check_urls(urls):
    pool = Pool(1)
    for url in urls:
        pool.spawn(fetch, url)
    pool.join()

def fetch(url):
    print url
    try:
        resp = requests.get(url, verify=False, timeout=5.0)
        print resp.status_code
    except socket.timeout:
        print "SocketTimeout"

check_urls(urls)

如果我删除了第一个2 lines,我的程序会打印SocketTimeout。但是对于monkeypatch,我的程序会永远等待。

有人能告诉我如何用monkeypatch捕获套接字超时异常吗?

1 个答案:

答案 0 :(得分:2)

问题是gevent默认超时设置为None。所以我们必须手动设置默认套接字超时。

from gevent import socket
socket.setdefaulttimeout(5)