Stopping a python program

user1330678 picture user1330678 · Apr 13, 2012 · Viewed 8.1k times · Source

I have a python program that displays battery voltages and temperatures in an electric car. I typically run it from a command line on a Mac by simply using the up arrow to find the command to change directory, and then up arrow to find the command to run the program. We figured out how to write a script that does this automatically and saved it as an application. It works great but don't know how to exit the program. I use control C when using the command line. How do I accomplish in in a script or app? I prefer not to ask our customers to use the command line.

Answer

David Robinson picture David Robinson · Apr 13, 2012
import sys; sys.exit()

will stop the Python program. When you call that code is up to you and depends on the details of your program (you could have it happen when a certain button is pressed, or after a certain amount of time, or when other conditions are met). Also be careful if you have to do any "clean-up" before the program ends- this also depends on the type of application.

If for some reason you want to stop it in exactly the same way as hitting Control-C, you could do

raise KeyboardInterrupt