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

threading.timer printing only last value of for loop

嘿,我被困在 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