2

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user1330678
  • 21
  • 1
  • 2
  • 3
    What kind of program is it? GUI? TUI? – Ignacio Vazquez-Abrams Apr 13 '12 at 04:26
  • Under what conditions do you want it to stop? It would be easy to have the program terminate after a certain amount of time, for example. Or do you want to give the end user some kind of graphical interface they can use to kill it? Perhaps a separate .py script they could double-click? – octern Apr 13 '12 at 04:31
  • The program is a realtim graphic display. The only reason for it to stop is when the customer is finished looking at it-- just like quitting Word or any other program. Since we have it run as a Mac app, we'd like it to quit by simply clicking on the red close dbutton. Would that be hard to do? – user1330678 Apr 13 '12 at 05:07
  • Do you have the actual Python code? Who wrote it? – David Robinson Apr 13 '12 at 22:28

1 Answers1

2
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
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • The program stops neatly with a control c from a command line, but now it runs without a terminal window, so we need to be able to quit the program with the red quit button. – user1330678 Apr 13 '12 at 05:11
  • 1
    Then like I say in the answer, make a red quit button that executes the code `import sys; sys.exit()`. How you make the red quit button depends entirely on the details of the application. – David Robinson Apr 13 '12 at 05:19