[英]how can I make a singular loop wait in python
我想让循环暂停 5 秒,但我有多个循环,所以如果我使用 time.sleep 另一个循环停止工作
while a==True:
b=b+1.5
print("Something: "+str(b))
time.sleep(5)
clear() #I defined a clear function to clear the screen
while a==True:
print("Something!") #here is the nonoperating part and I tested it doesn't gets cleared by clear function
我假设您希望两个循环同时运行。 所以在它自己的线程中运行每个循环:
from threading import Thread
import time
def clear():
pass # some implementation
a = True
b = 0.0
def fun():
global b
while a==True:
b=b+1.5
print("Something: "+str(b))
time.sleep(5)
clear() #I defined a clear function to clear the screen
t = Thread(target=fun, daemon=True) # thread will end when main thread terminates
t.start()
while a==True:
time.sleep(1) # for demo purposes
print("Something!")
使用 time.sleep 的问题是,这是一个阻塞函数,它不能在后台与另一块代码同步运行。 有两种方法可以克服这个问题:
在我看来,您的问题看起来是使用 asyncio 解决的一个很好的例子:
import asyncio
async def function1():
while a: # You can leave out '==True', as 'while a' alone will do the job
b += 1.5
print("Something {}".format(b))
await asyncio.sleep(5)
clear()
async def function2():
while a:
print("Something!")
await asyncio.sleep() # give the loop function some time to sleep, be it just so tiny. Otherwise yout program will never be able to swith between loops
if __name__=="__main__":
asyncio.run(\
asyncio.gather(\
function1(),
function2(),
return_exceptions=True
)
)
通过使用 asyncio,您可以实现协作式多任务处理,或者换句话说,在一个进程中的一个线程中拥有一个函数,在后台同时监督多个协程,但一次只执行一个。
这很适合您的问题,因为您主要是在等待一些时间在不同位代码的执行之间传递,而不是真正要求“真正的”同时进行多处理。 通过不使用线程或进程,您将减少程序占用的资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.