自脚本启动以来,我想在不同的时间安排文本“hello world”(形成一个列表)。最好的方法是什么?
这可能是错误的,但到目前为止我所拥有的:
import time
times = [1.76493425, 3.10174059, 4.49576803, 10.99379224, 18.84178369] #at these times since onset of script, a text "hello world" should be printed
start = time.time()
def main():
for cuetime in times:
print ('hello world', ' - timing: ', cuetime, ' - now: ', time.time()- start)
yield viztask.waitTime(cuetime)
main()
这给了我:
('hello world', ' - timing: ', 1.76493425, ' - now: ', 0.0)
('hello world', ' - timing: ', 3.10174059, ' - now: ', 1.7699999809265137)
('hello world', ' - timing: ', 4.49576803, ' - now: ', 3.5379998683929443)
('hello world', ' - timing: ', 10.99379224, ' - now: ', 5.305999994277954)
('hello world', ' - timing: ', 18.84178369, ' - now: ', 7.075000047683716)
但我真正需要的是时间元素/项目与“现在”时间相同,因为时间列表中的元素是相对于开始打印文本“hello world”的时间脚本的。
最佳答案
查看sched
图书馆了解更多详情。这是一个代码示例,它不是 100% 准确,但如果您不需要毫秒精度,应该可以解决问题。
import time
import sched
def print_time(cuetime):
global start
print ('hello world', ' - timing: ', cuetime, ' - now: ', time.time()- start)
start = time.time()
times = [1.76493425, 3.10174059, 4.49576803, 10.99379224, 18.84178369]
if __name__ == "__main__":
s = sched.scheduler(time.time, time.sleep)
for cuetime in times:
s.enter(cuetime, 1, print_time, (cuetime,))
s.run()
关于python - 在脚本以 Python 启动后,在特定时间安排打印命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274851/