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

时间:2017-03-07 17:36:10

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

嘿,我陷入了一种情况,我有条件内部循环。如果条件满足,我希望输出延迟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

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

1 个答案:

答案 0 :(得分:3)

问题在于你的范围。在定时器之后,延迟功能将打印当前的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语句中调用延迟函数。

实际上,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