[英]python - printing something in a for loop every n seconds
I have a for loop that iterates over a number and performs some simple calculations. 我有一个for循环迭代一个数字并执行一些简单的计算。 I am trying to figure out how to print out ( or log to file) the current value of 'val' every .5 to 1 second with out having to pause or sleep during the loop. 我试图弄清楚如何打印(或记录到文件)'val'的当前值每0.5到1秒,而不必在循环期间暂停或睡眠。 Here is a super simple example 这是一个非常简单的例子
val_list = []
for i in xrange(iterations):
val = (i*(1/2)) * pi
val2 = np.linalg.pinv(val)
# print or write to log val2 after every half second (or 1 second)
val_list.append(val2)
Just use time.time
to capture the time before starting, then check how long it's been after you calculate val2: 只需使用time.time
来捕获开始前的时间,然后检查计算val2后的时间:
import time
val_list = []
prev_time = time.time()
for i in xrange(iterations):
val = (i*(1/2)) * pi
val2 = np.linalg.pinv(val)
# print or write to log val2 after every half second (or 1 second)
dt = time.time() - prev_time
if dt > 1:
# print or write to log here
prev_time = time.time()
val_list.append(val2)
You can use time.time()
: 你可以使用time.time()
:
from time import time as t
val_list = []
nowTime = t()
for i in xrange(iterations):
val = (i*(1/2)) * pi
val2 = np.linalg.pinv(val)
curTime = t()
if curTime - nowTime >= 0.5:
#Do your stuff
nowTime = curTime
val_list.append(val2)
You can achieve this using Threads. 你可以使用Threads来实现这一点。
Here's a documentation on how to utilize Threads : https://docs.python.org/3/library/threading.html ( If you're using Python2.7 then change the 3 in the url to a 2 ) 这是一个关于如何利用线程的文档: https : //docs.python.org/3/library/threading.html (如果你使用的是Python2.7,那么将网址中的3更改为2)
Here's a link which is similar to what you want and should also point you in the right direction : Python threading.timer - repeat function every 'n' seconds 这是一个类似于你想要的链接,也应该指向正确的方向: Python threading.timer - 每隔'n'秒重复一次功能
Basically you have to create a Thread that will only execute ever n number of seconds. 基本上你必须创建一个只执行n秒的Thread。 On each iteration it will print the value. 在每次迭代时,它将打印该值。 The above link should suffice for that. 上面的链接就足够了。 Good luck ! 祝好运 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.