首页 > 解决方案 > 如果没有脚本正在运行,则在 shell 中处理 KeyboardInterrupt

问题描述

如果没有脚本正在运行,是否可以在 shell 中处理 KeyboardInterrupt?

我的问题的背景如下:我使用python通过套接字连接向电机控制器发送命令。该函数将电机的目标位置发送到控制器并立即返回,即在电机实际到达其目标位置之前。现在可能会发生用户输入错误位置并希望尽快中断电机运动的情况。这可以通过输入 stop() 来完成,它会向控制器发送停止命令。但是如果可以通过按Ctrl+C来停止电机会更直观更快。有没有办法让python在没有脚本运行的情况下通过按Ctrl+C来执行一个函数?

我知道如何在正在运行的脚本中处理 KeyboardInterrupt 异常或 signal.SIGINT,但找不到任何关于如何解决我的目标的提示。

如果有任何帮助,我将不胜感激!

标签: pythonkeyboardinterrupt

解决方案


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.


推荐阅读