我正在尝试给您一个进度指示器,其中一项任务正在执行某项操作,而另一项任务正在执行一项进度。我的世界问候版在其中一项任务中进入睡眠状态,但从未唤醒。
我想念什么?
非常感谢
import asyncio
import sys
import time
import itertools
progress = True
def get_progress():
return progress
async def define_progress():
print("progress started")
await asyncio.sleep(2)
progress = False
print("progress ended")
async def run_spinner(msg):
spinner = itertools.cycle(['-', '/', '|', '\\'])
sys.stdout.write("{0} ".format(msg))
while(get_progress()):
sys.stdout.write("{0}".format(next(spinner)))
sys.stdout.flush()
time.sleep(0.3)
sys.stdout.write('\b')
async def main():
msg = "start logic"
await asyncio.gather(run_spinner(msg), define_progress())
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
第二行无限运行微调器时,输出如下所示。
进度开始了
正在创建软件包\
答案 0 :(得分:1)
我必须使 progress 成为全局变量,并将await asyncio.sleep(1)添加到run_spinner。我不确定这是否能回答您的问题,但它确实可以满足您的要求。
import asyncio
import sys
import time
import itertools
global progress
progress = True
def get_progress():
global progress
return progress
async def define_progress():
global progress
print("progress started")
await asyncio.sleep(2)
progress = False
print("progress ended")
async def run_spinner(msg):
spinner = itertools.cycle(['-', '/', '|', '\\'])
sys.stdout.write("{0} ".format(msg))
while(get_progress()):
sys.stdout.write("{0}".format(next(spinner)))
sys.stdout.flush()
time.sleep(0.2)
sys.stdout.write('\b')
await asyncio.sleep(1)
async def main():
msg = "start logic"
await asyncio.gather(run_spinner(msg), define_progress())
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()