python - 使用 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
解决方案
您需要在单独的线程中运行每个循环,否则它们将以顺序方式执行,即第一个循环然后是第二个循环(永远不会执行,因为第一个循环永远执行)。
例如:
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()
推荐阅读
- css - 无法以角度获取openlayers css
- linux - 如何查找具有特定名称的所有子目录并删除其内容(而不是删除目录本身)
- coq - Coq 中的 b/w 等变和协变箭头有什么区别?
- amazon-web-services - 带参数的 appsync 订阅
- django - 在服务器私有 IP/vpn 隧道上访问 Django 应用程序
- loopbackjs - tp 如何从 loopback.js 远程方法发送大数据集
- ruby - 如何过滤对象数组
- tensorflow - GPU 中的 Bfloat16 训练
- python - 如何在 Python 中显示数字的最后 2 位数字
- python-3.x - 尝试将 Yelp API 用于 business_id 以外的其他内容