简体   繁体   中英

Python trap routine

Alright so for a living I program ABB industrial robots , and the programming language we use is called Rapid .

One really cool thing I can do in Rapid is called a trap routine. 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.

I suppose it is similar to an event listener in javascript. It's like it runs in the background of the normal program. I want to do this in python.

I have little formal CS education so I'm not exactly sure what this concept is. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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