Python threading.timer仅打印for循环的最后一个值
嘿,我被困在一个情况下,我有如果条件内为循环。如果条件满足,我希望得到10秒延迟的输出。而不是期望的输出,我得到所有的值在同一时间,然后最后一个值重复10秒的延迟。下面是代码Python threading.timer仅打印for循环的最后一个值,python,multithreading,python-3.x,for-loop,python-multithreading,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.T
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
如果我能在这里得到一些帮助,我将非常感激。谢谢问题在于您的范围。定时器启动后,delayfunction将打印当前的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语句中调用delayfunction
事实上,threading.Timer将在10秒后(作为第一个参数)调用您的函数(作为第二个参数)
将输出:
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
非常感谢这正是我想要的。多谢各位much@AhsanNaseem:欢迎来到StackOverflow。如果某人的答案解决了您的问题,则将此答案标记为“已接受”(使用投票小部件下的绿色复选标记)。它赞扬了答案的作者,并让社区知道这个问题已经解决。
threading.Timer
在这里似乎有点过头了。为什么不仅仅是time.sleep(10)
?@twalberg因为睡眠会保存整个脚本,我想要实现的是脚本继续运行,但在特定时间后运行某些属性。谢天谢地,我得到了下面的答案。啊,那就有道理了。问题中没有真正说明。。。
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