简体   繁体   English

Python陷阱例程

[英]Python trap routine

Alright so for a living I program ABB industrial robots , and the programming language we use is called Rapid . 好的,这样我就可以为ABB工业机器人编程,而我们使用的编程语言称为Rapid

One really cool thing I can do in Rapid is called a trap routine. 我在Rapid中可以做的一件非常酷的事情称为陷阱例程。 And it's like a while loop but instead of looping through the whole loop before it checks a condition it will break literally as soon as the event its waiting for happens. 这就像一个while循环,而不是在检查条件之前遍历整个循环,它会在等待事件发生时立即中断。

I suppose it is similar to an event listener in javascript. 我想它类似于javascript中的事件监听器。 It's like it runs in the background of the normal program. 就像它在普通程序的后台运行一样。 I want to do this in python. 我想在python中做到这一点。

I have little formal CS education so I'm not exactly sure what this concept is. 我几乎没有进行过CS的正规教育,所以我不确定这个概念是什么。 Sorry if it's a bit vague I'm not really sure how to ask it in a clear way. 抱歉,如果有点含糊,我不确定如何以明确的方式提出。

Like most languages, so does Python handle system signals by using handler functions. 像大多数语言一样,Python也通过使用处理函数来处理系统信号 For more details, take a look at the Signals chapter which talks about receiving and sending signals, with examples eg here . 有关更多详细信息,请参阅“ 信号”一章 ,其中讨论了接收和发送信号,例如此处

In short, you can bind a function to one or more signals: 简而言之,您可以将函数绑定到一个或多个信号:

>>> 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

In your specific case, find out which signal(s) the robot sends to your Python process (or whichever process listens to signals) and then act on them as shown above. 在您的特定情况下,找出机器人发送到您的Python进程(或哪个进程侦听信号)的信号,然后对它们进行操作,如上所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM