python – 协同程序的Asyncio打印状态进度
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 协同程序的Asyncio打印状态进度,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2110字,纯文字阅读大概需要4分钟。
内容图文
![python – 协同程序的Asyncio打印状态进度](/upload/InfoBanner/zyjiaocheng/787/c248321b73d940e293d7d172df6d1934.jpg)
我有一堆协同作用做一些工作
@asyncio.coroutine
def do_work():
global COUNTER
result = ...
if result.status == 'OK':
COUNTER += 1
还有一个
COUNTER = 0
@asyncio.coroutine
def display_status():
while True:
print(COUNTER)
yield from asyncio.sleep(1)
必须显示有多少协同程序完成了他们的工作.如何正确实施这项任务?以下解决方案无效
@asyncio.coroutine
def spawn_jobs():
coros = []
for i in range(10):
coros.append(asyncio.Task(do_work()))
yield from asyncio.gather(*coros)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(display_status())
loop.run_until_complete(spawn_jobs())
loop.close()
我希望无论do_work()协同程序做什么,计数器都会每秒打印到控制台.但我只有两个输出:0和几秒后重复10.
解决方法:
But I have just two outputs: 0 and after a few seconds repeating 10.
我无法重现它.如果我使用:
import asyncio
import random
@asyncio.coroutine
def do_work():
global COUNTER
yield from asyncio.sleep(random.randint(1, 5))
COUNTER += 1
我得到这样的输出:
0
0
4
6
8
Task was destroyed but it is pending!
task: <Task pending coro=<display_status() running at most_wanted.py:16> wait_for=<Future pending cb=[Task._wakeup()] created at ../Lib/asyncio/tasks.py:490> created at most_wanted.py:27>
display_status()中的无限循环会在最后导致警告.避免警告;完成批处理中的所有任务后退出循环:
#!/usr/bin/env python3
import asyncio
import random
from contextlib import closing
from itertools import cycle
class Batch:
def __init__(self, n):
self.total = n
self.done = 0
async def run(self):
await asyncio.wait([batch.do_work() for _ in range(batch.total)])
def running(self):
return self.done < self.total
async def do_work(self):
await asyncio.sleep(random.randint(1, 5)) # do some work here
self.done += 1
async def display_status(self):
while self.running():
await asyncio.sleep(1)
print('\rdone:', self.done)
async def display_spinner(self, char=cycle('/|\-')):
while self.running():
print('\r' + next(char), flush=True, end='')
await asyncio.sleep(.3)
with closing(asyncio.get_event_loop()) as loop:
batch = Batch(10)
loop.run_until_complete(asyncio.wait([
batch.run(), batch.display_status(), batch.display_spinner()]))
产量
done: 0
done: 2
done: 3
done: 4
done: 10
内容总结
以上是互联网集市为您收集整理的python – 协同程序的Asyncio打印状态进度全部内容,希望文章能够帮你解决python – 协同程序的Asyncio打印状态进度所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。