Python陷阱例程

时间:2018-09-11 05:41:43

标签: python events event-handling

好吧,对于我来说,我正在编程ABB industrial robots,而我们使用的编程语言称为Rapid

我在Rapid中可以做的一件很酷的事情叫做陷阱例程。这就像一个while循环,而不是在检查条件之前遍历整个循环,它会在等待事件发生时立即中断。

我想它类似于javascript中的事件监听器。就像它在普通程序的后台运行一样。我想在python中做到这一点。

我几乎没有正规的CS教育,所以我不确定这个概念是什么。抱歉,如果有点含糊,我不确定如何以明确的方式提出。

1 个答案:

答案 0 :(得分:0)

与大多数语言一样,Python也通过使用处理函数来处理system signals。有关更多详细信息,请参见Signals chapter,其中举例说明了接收和发送信号。 here

简而言之,您可以将函数绑定到一个或多个信号:

>>> import signal
>>> import sys
>>> import time
>>> 
>>> # Here we define a function that we want to get called.
>>> def received_ctrl_c(signum, stack):
...     print("Received Ctrl-C")
...     sys.exit(0)
... 
>>> # Bind the function to the standard system Ctrl-C signal.
>>> handler = signal.signal(signal.SIGINT, received_ctrl_c)
>>> handler
<built-in function default_int_handler>
>>> 
>>> # Now let’s loop forever, and break out only by pressing Ctrl-C, i.e. sending the SIGINT signal to the Python process.
>>> while True:
...     print("Waiting…")
...     time.sleep(5)
... 
Waiting…
Waiting…
Waiting…
^CReceived Ctrl-C

在您的特定情况下,找出机器人发送到您的Python进程的信号(或哪个进程侦听信号),然后对它们进行操作,如上所示。