Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to capture gevent socket timeout exception

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)

If I remove the first 2 lines, my program printing SocketTimeout. But with monkeypatch, my program waits forever.

Can someone tell me how to capture that socket timeout exception with monkeypatch?

like image 601
PrivateUser Avatar asked Mar 10 '26 23:03

PrivateUser


1 Answers

Problem was gevent default timeout set to None. So we have to set default socket timeout manually.

from gevent import socket
socket.setdefaulttimeout(5)
like image 86
PrivateUser Avatar answered Mar 12 '26 12:03

PrivateUser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!