【发布时间】:2020-05-14 01:13:49
【问题描述】:
我正在尝试执行一个在 python 中激活冷却计时器的命令,但我遇到了问题。它锁定了整个程序,在冷却结束之前不再允许任何其他输入。我希望能够在循环等待 X 秒通过时输入更多命令。
例子:
import asyncio
import time
count = 0
cool = 0
async def main():
global count
while True:
userinput = input("enter command")
if userinput == "test":
count = count + 1
print("did test: " + str(count) + " times.")
if count >= 3:
await cooldown())
while count >= 3:
if cool == 0:
count = 0
else:
print("Command still on cooldown.")
else:
print("not a real command")
async def cooldown():
global cool
cool = 1
print("Cooldown is activated.")
time.sleep(3)
cool = 0
print("Cooldown is deactivated.")
asyncio.run(main())
【问题讨论】:
-
time.sleep() 阻塞,你应该使用 asyncio.sleep
-
尝试使用 async.io sleep 和 time.sleep 仍然会阻塞程序。
标签: python python-3.x asynchronous python-asyncio