python的協程,monkeyPatch


monkey patch 一般指運行時候進行動態替換.
基本上我們使用gevent,會在最開頭的地方加入gevent.monkey.patch_all();把標准庫中的thread/socket等給替換掉.這樣我們在后面使用socket的時候它會變成非阻塞的了.而我們卻什么也不用做.

一個案列


from gevent import monkey; monkey.patch_all()
import gevent
from urllib import request



def run_task(url):
    print("開始訪問 --> %s" % url)
    try:
        response = request.urlopen(url)
        data = response.read()
        print("{} bytes received from {}".forma(len(data), url))
    except Exception:
        print("訪問中出錯了")

if __name__ == '__main__':
    urls = ['https://baidu.com/', 'https://github.com','https://blog.csdn.net/', 'https://cnblogs.com/lovesKey']
    # 定義協程方法
    greenlets = [gevent.spawn(run_task, url) for url in urls]
    # 添加協程任務,並且啟動運行
    gevent.joinall(greenlets)

最快訪問結束的會在第一位,最慢的會在最后一位.
輸出結果:

Visit --> https://baidu.com/
Visit --> https://github.com
Visit --> https://blog.csdn.net/
Visit --> https://cnblogs.com/lovesKey
154097 bytes received from https://baidu.com/.
26813 bytes received from https://cnblogs.com/lovesKey.
155908 bytes received from https://blog.csdn.net/.
86916 bytes received from https://github.com.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM