Python全栈开发:协程代码实例

时间:2024-11-24 23:03:25

协程代码1

#!/usr/bin/env python
# -*- coding;utf-8 -*-
# 导入协程模块
"""
协程工作原理
"""
import greenlet
from greenlet import greenlet def text1():
print(12)
gr2.switch()
print(56)
gr2.switch() def text2():
print(34)
gr1.switch()
print(78) gr1 = greenlet(text1)
gr2 = greenlet(text2) gr1.switch()

协程代码2

#!/usr/bin/env python
# -*- coding;utf-8 -*-
"""
使用协程模块gevent自动切换线程,注意调入模块的方式:
from gevent import monkey;monkey.patch_all()
"""
import time
from gevent import monkey;monkey.patch_all()
import gevent
import requests def f(url):
print("Get: %s" % url)
ret = requests.get(url)
date = ret.text
print(len(date)) links = []
with open("G:/python/urls.txt", "r") as url:
for i in url:
links.append(gevent.spawn(f, i)) gevent.joinall(links)