Reputation: 41
Is it possible to handle KeyboardInterrupt in the shell if no script is running?
The background of my question is the following: I use python to send commands to a motor controller via a socket connection. The function sends a target position of a motor to the controller and immediately returns, i.e. before the motor actually reaches its target position. Now it can happen that a user enters a wrong position and wants to interrupt the motor motion as quick as possible. This could be done by typing stop() which sends a stop command to the controller. But it would be more intuitive and faster if the motor could be stopped by pressing Ctrl+C. Is there a way to let python execute a function by pressing Ctrl+C while no script is running?
I know how to handle the KeyboardInterrupt exception or the signal.SIGINT within a running script, but could not find any hints on how to solve my goal.
I would be very grateful for any help!
Upvotes: 0
Views: 889
Reputation: 36781
If the controller can handle having multiple connections to the socket, you can launch an entire new process that makes use of the keyboard
module to listen for ctrl+c
and then have that process send the stop command to controller.
First install the keyboard package from pypi
pip install keyboard
Create a file to listen for ctrl+c
:
# file named 'wait_stop.py
##########################
import keyboard
# code here to establish connection to controller
def wait_stop():
keyboard.wait('ctrl+c')
print('sending stop signal')
# function that sends stop signal here...
# ...
# call wait_stop again to continue listening.
wait_stop()
if __name__ == '__main__':
wait_stop()
Now you can launch the process in a separate shell via:
python wait_stop.py
As long as the wait_stop
process shell is NOT the active window, hitting ctrl+c
will cause send the stop()
function to the controller. If the window is active, it will also kill the wait_stop.py
process.
Upvotes: 1
Reputation: 1148
KeyboardInterrupt send SIGINT
signal (code 2).
So instead of hitting CTRL+C you could send KeyboardInterrupt with kill -2 <pid>
.
To display your program pid use os.getpid()
.
Upvotes: 0