python - threading.timer 只打印 for 循环的最后一个值

标签 python multithreading python-3.x for-loop python-multithreading

嘿,我陷入了一种情况,我在 for 循环中有 if 条件。如果条件满足,我想延迟 10 秒获得输出。我没有获得所需的输出,而是同时获得所有值,然后最后一个值以 10 秒的延迟重复。下面是代码

import threading
import time
a=[2, 3, 4, 10, 12]
b=2
for x in a:
    if x >2:
        def delayfunction():
            print(x,"is not ok")
        threading.Timer(10, delayfunction).start()
        delayfunction()
    else:
        print(x," is less than equal to 2")

输出是:

2  is less than equal to 2
3 is not ok
4 is not ok
10 is not ok
12 is not ok
12 is not ok
12 is not ok
12 is not ok
12 is not ok

如果能在这里得到一些帮助,我将不胜感激。谢谢

最佳答案

问题是你的范围。在计时器之后,延迟函数将打印当前 x 值,而不是计时器开始时的 x 值。

你需要像这样传递 x 作为参数:

import threading
import time
a=[2, 3, 4, 10, 12]
b=2
for x in a:
    if x >2:
        def delayfunction(current_x):
            print(current_x,"is not ok")
        threading.Timer(10, delayfunction, [x]).start()
        delayfunction(x)
    else:
        print(x," is less than equal to 2")

输出将是:

2  is less than equal to 2
3 is not ok
4 is not ok
10 is not ok
12 is not ok
3 is not ok
4 is not ok
10 is not ok
12 is not ok

如果你不想在定时器之前输出,就不要在你的 if 语句中调用你的 delay 函数。

事实上,threading.Timer 将在 10 秒(作为第一个参数给出)后调用您的函数(作为第二个参数给出)

import threading
import time
a=[2, 3, 4, 10, 12]
b=2
for x in a:
    if x >2:
        def delayfunction(current_x):
            print(current_x,"is not ok")
        threading.Timer(10, delayfunction, [x]).start()
    else:
        print(x," is less than equal to 2")

将输出:

2  is less than equal to 2 # immediatly
3 is not ok                # before 10 second
4 is not ok                # before 10 second
10 is not ok               # before 10 second
12 is not ok               # before 10 second

关于python - threading.timer 只打印 for 循环的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42654665/

相关文章:

python - 在 Keras 中修改图层权重

java - 如何证明java中的HashMap不是线程安全的

Python - 串行进程、多线程、多进程都需要相同的时间在我的本地运行

python - 具体模型阅读 xlsx 文档 Pyomo

python - 如果存在字符则拆分字符串,否则不拆分

python-2.7 - 什么是sys._MEIPASS

python - pandas groupby 滚动行为

python - 一个python虚拟环境和具体的系统库有什么关系?

Python — 如何找到下三角 ​​numpy 矩阵的方阵? (具有对称的上三角形)

c++ - 如何检查线程中是否调用了析构函数?