我需要一种替代方法来“延迟”循环上的操作。当使用 time.sleep(1) 时,整个过程会暂停一秒钟。 print 'something'
应每 1 秒执行一次,执行 50 次,并且不会中断进程的其余部分。
实际代码:
for num in range(50, -1, -1):
print 'something'
time.sleep(1)
最佳答案
如果我明白你想要什么,你需要使用线程。一个线程将完全执行您所做的操作:仅计数并休眠。另一个线程将是“进程的其余部分”,做它想做的任何事情,而不会被 sleep 中断。
import time
import threading
def count():
for num in range(50, -1, -1):
print 'something'
time.sleep(1)
count_thread = threading.Thread(target=count)
count_thread.start()
for num in range(10, -1, -1):
print 'main'
time.sleep(5)
count_thread.join()
关于Python 循环延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32065027/