import gevent





import
gevent,time ##gevent 是 第三方库 from gevent import monkey from urllib import request monkey.patch_all() ## 让程序变成IO def libs(url): print('Get %s '%url) requ = request.urlopen(url) re_requ = requ.read() urls = ['https://www.python.org/', 'https://www.yahoo.com/', 'https://github.com/' ] time_star = time.time() for i in urls: libs(i) print('损耗的时间是 %s'%(time.time()-time_star)) ootime = time.time() gevent.joinall([ gevent.spawn(libs,'https://www.python.org/'), gevent.spawn(libs,'https://www.yahoo.com/'), gevent.spawn(libs,'https://github.com/'), ]) print('异步所需的时间是 %s'%(time.time()-ootime))

结果

F:python_oldboyScriptspScriptspython.exe F:/python_oldboy/geve/爬虫练习.py
Get https://www.python.org/
Get https://www.yahoo.com/
Get https://github.com/
损耗的时间是 10.494600296020508
Get https://www.python.org/
Get https://www.yahoo.com/
Get https://github.com/
异步所需的时间是 3.925224542617798


import gevent
##安装第三方库  gevent, 可实现 同步或者异步编程
def foo():
    print('Running in foo')  #1
    gevent.sleep(2)
    print('context switch to foo again') #4

def bar():
    print('running in bar')  #2
    gevent.sleep(1)
    print('context switch back bar') #3

gevent.joinall([
    gevent.spawn(foo),gevent.spawn(bar)
])
原文地址:https://www.cnblogs.com/th-lyc/p/8848490.html