python - 如果没有脚本正在运行,则在 shell 中处理 KeyboardInterrupt
问题描述
如果没有脚本正在运行,是否可以在 shell 中处理 KeyboardInterrupt?
我的问题的背景如下:我使用python通过套接字连接向电机控制器发送命令。该函数将电机的目标位置发送到控制器并立即返回,即在电机实际到达其目标位置之前。现在可能会发生用户输入错误位置并希望尽快中断电机运动的情况。这可以通过输入 stop() 来完成,它会向控制器发送停止命令。但是如果可以通过按Ctrl+C来停止电机会更直观更快。有没有办法让python在没有脚本运行的情况下通过按Ctrl+C来执行一个函数?
我知道如何在正在运行的脚本中处理 KeyboardInterrupt 异常或 signal.SIGINT,但找不到任何关于如何解决我的目标的提示。
如果有任何帮助,我将不胜感激!
解决方案
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.
推荐阅读
- javascript - 复制谷歌日历事件弹出面板的相同位置功能
- node.js - 如何热模块替换我正在服务器端开发的本地 npm 包呈现反应,node.js 应用程序,例如在 cezerin
- python-3.x - 在 TensorFlow 中使用多个 GPU 使用 pb 模型进行推理
- typescript - 打字稿接口:可选但不是未定义
- php - Mysql 和 php 数据库连接
- node.js - 安装 .env 模块后节点/反应,“fs”错误
- c# - 比较两个数组并从第二个数组中删除相同(相交)的值
- html - Angular 7 + Material:在表单数据中使用多个 mat-checkbox 时,只有在与它们交互后才将它们加载到字段中
- java - 是否可以在 jpa AttributeConverter 中获取 @Convert 注释的字段?
- java - java泛型引起的ClassCastException如何解决