简体   繁体   English

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

[英]threading.timer printing only last value of for loop

Hey I am stuck in a situation where I have if condition inside for loop. 嘿,我陷入了一种情况,我有条件内循环。 I wanted to get output with 10 seconds delay if condition satisfies. 如果条件满足,我希望输出延迟10秒。 Instead of desired output I get all values at same time and then last value repeats with 10 second delay. 而不是期望的输出,我同时获得所有值,然后最后的值重复10秒延迟。 Below is code 下面是代码

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")

output is: 输出是:

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

I will be very much grateful if could get some assist here. 如果能在这里得到一些帮助,我将非常感激。 Thanks 谢谢

The problem is your scope. 问题是你的范围。 After the timer, the delayfunction will print the current x value, not the value of x at the start of the timer. 在定时器之后,延迟功能将打印当前的x值,而不是定时器启动时的x值。

You need to pass the x as argument like this: 您需要将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")

The output will be: 输出将是:

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 you don't want the output before the timer, just don't call your delayfunction in your if statement. 如果您不想在计时器之前输出,只是不要在if语句中调用延迟函数。

In fact, threading.Timer will call your function (given as second parameter) after the 10 seconde (given as first parameter) 实际上,threading.Timer会在10次seconde之后调用你的函数(作为第二个参数给出)(作为第一个参数给出)

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")

will output: 将输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM