简体   繁体   中英

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?

How do I capture C at any (unpredicted) point in the program?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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