Python中的实时中断 [英] Real-time interrupts in Python
问题描述
我有一个运行无限while循环的Python 2.7程序,我想合并一个计时器中断. 我的目的是在循环中的某个时刻触发一个计时器,当5秒钟过去后,我希望代码跳转到while循环的特定部分.
I have a Python 2.7 program running an infinite while loop and I want to incorporate a timer interrupt. What I aim to do is to set off a timer at some point in the loop, and when 5 seconds have elapsed I want the code to branch to a specific part of the while loop.
到目前为止,我一直在做以下事情: 在while循环的每次迭代中,我都在检查使用代码到达该点时经过了多少时间
What I have been doing so far is the following: in each iteration of the while loop I am checking how much time has elapsed when I reach that point in the code using
time.clock()
如果差异超过5,我将运行我打算运行的代码块
and if the difference exceeds 5 I run the chunk of code I mean to run
但是,在我评估时间之前可能要经过7秒,这将是> 5秒,但我想在5秒过去后准确地到达该地点
However that way 7 seconds might pass before I evaluate the time, it will be >5sec but I want to go there exactly when 5 seconds pass
此外,我需要为1个以上的计数器(可能最多为100个)工作,但我不希望中断彼此中断.使用Timer也不起作用.
Also, I need this to work for more than 1 counter (possibly up to a 100) but I do not want the interrupts to interrupt each other. Using Timer did not work either.
我知道这可以通过在汇编中使用计时器中断来完成,但是我该如何在python中做到这一点呢?
I know this can be done using timer interrupts in assembly but how can I do that in python?
推荐答案
如果要处理单个事件,则最简单的方法是使用signal
框架,该框架是
If a single event is to be handled, then the easiest way is to use the signal
framework which is a standard module of Python.
但是,如果我们需要一个成熟的调度程序,那么我们就不得不求助于另一个模块:sched
. 此处是官方文档的指针.但是请注意,在多线程环境中,sched
在线程安全性方面有局限性.
However, if we need a fully-fledged scheduler, then we have to resort to another module: sched
. Here is a pointer to the official documentation. Please be aware, though, that in multi-threaded environments sched
has limitations with respect to thread-safety.
另一个选项是高级Python计划程序,它不属于标准发行版.
Another option is the Advanced Python Scheduler, which is not part of the standard distribution.
这篇关于Python中的实时中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!