Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 image 951
Robotica Avatar asked Jun 04 '26 16:06

Robotica


1 Answers

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 e.g. 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.

like image 191
Jens Avatar answered Jun 07 '26 22:06

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!