gevent實現異步

test_gevent.py

import gevent
import requests
import time
from gevent import monkey
monkey.patch_all()


def f(url, i):
    print('{} GET: {}'.format(i, url))
    resp = requests.get(url)
    time.sleep(0.5)
    print('{} success'.format(i))
    return resp

tasks = [
        gevent.spawn(f, 'http://www.baidu.com/', 1),
        gevent.spawn(f, 'http://www.163.com/', 2),
]
gevent.joinall(tasks)
for t in tasks:
    print(t.value)

輸出:

1 GET: http://www.baidu.com/
2 GET: http://www.163.com/
1 success
2 success
<Response [200]>
<Response [200]>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章