简体   繁体   English

Python。 我如何捕捉<cntl> C 在程序的任何地方,然后清理?</cntl>

[英]Python. How do I capture <cntl>C anywhere in a program, then clean up?

I am developing a program to control a machine.我正在开发一个程序来控制一台机器。 Frequently the movement needs to be stopped before it does harm.经常需要在运动造成伤害之前停止运动。 At the moment, immediate control is by switching off the power because the machine continues to respond to stored commands.目前,立即控制是通过关闭电源,因为机器继续响应存储的命令。 This leaves a lot of loose ends.这留下了很多松散的结局。 I need to send a command to stop the machine immediately, and clear the queue before it can be started up.我需要发送命令立即停止机器,并在启动之前清除队列。 This can happen at any time/place during the running of the program.这可以在程序运行期间的任何时间/地点发生。

All the examples I have seen here appear to assume that the placing of the C and keyboardinterrupt response is predicable, eg How do I capture SIGINT in Python?我在这里看到的所有示例似乎都假设 C 和键盘中断响应的放置是可预测的,例如如何在 Python 中捕获 SIGINT?

How do I capture C at any (unpredicted) point in the program?如何在程序中的任何(未预测的)点捕获 C?

This question reveals that I don't really understand how the underlying processes work.这个问题表明我并不真正了解底层流程是如何工作的。

You could execute all of your code within a "main" function and catch it within an except.您可以在“主要” function 中执行所有代码,并在异常中捕获它。

def Main():
    # Running code...

try:
    Main()
except KeyboardInterrupt:
    # Execute actions to stop immediately.
except Exception as e:
    print("An unexpected error occurred:\n" + str(e)) 
    # Execute actions to stop immediately.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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