如何处理 GRequests 中的错误?

How to handle errors in GRequests?

我有这个代码

#!/usr/bin/python

import grequests

urls = [
'http://google.com',
'http://doesnotexists.tld'
]


def do_something(response, **kwargs):
        print response.text

async_list = []

for u in urls:
    action_item = grequests.get(u, timeout=10, hooks = {'response' : do_something})
    async_list.append(action_item)

grequests.map(async_list,size=10)

如何在不收到常见的 Python 错误消息的情况下处理错误?
例如,对于不存在的域,它会打印出 "not found".

从 pypi(使用 pip)安装的 grequests 似乎不包括异常处理。但是 github 的版本已经实现了该功能:

def map(requests, stream=False, size=None, exception_handler=None)

因此您应该克隆 grequests 或从 github 下载 grequests.py 并使用该版本。您可以直接使用 pip 安装该版本:

pip install git+https://github.com/kennethreitz/grequests.git

如果您正在寻找异常处理示例,您可以查看存储库中的 test.py。 https://github.com/kennethreitz/grequests/blob/master/tests.py

最新版本的 grequests 已修复此问题 - https://github.com/kennethreitz/grequests