首页 > 解决方案 > 使用 time.sleep 运行 2 个分开的代码,带有几个巧妙的循环

问题描述

我有一些问题,我需要在 while 循环中运行单独的代码

例子:

    import time
while True:
    time.sleep(5)

    print('\ntime 5 s')

while True:
    time.sleep(1)
    print('\ntime 1 s')

我知道,这不起作用,但如何像这样的输出启动它:

time 1 s
time 1 s
time 1 s
time 1 s
time 1 s
time 5 s

标签: pythonpython-3.x

解决方案


您需要在单独的线程中运行每个循环,否则它们将以顺序方式执行,即第一个循环然后是第二个循环(永远不会执行,因为第一个循环永远执行)。

例如:

import time
import threading

def func1():
    while True:
        time.sleep(1)
        print('\ntime 1 s')

def func5():
    while True:
        time.sleep(5)
        print('\ntime 5 s')

threads = [threading.Thread(target=func) for func in [func1,func5]]
for thread in threads: thread.start()
for thread in threads: thread.join()

推荐阅读