簡體   English   中英

threading.timer只打印for循環的最后一個值

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

嘿,我陷入了一種情況,我有條件內循環。 如果條件滿足,我希望輸出延遲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語句中調用延遲函數。

實際上,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")

將輸出:

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