Graceful exiting of a program in Python?

And I'm assuming you mean killing from outside the python script.

The way I've found easiest is

@atexit.register
def cleanup()
  sys.unlink("myfile.%d" % os.getpid() )

f = open("myfile.%d" % os.getpid(), "w" )
f.write("Nothing")
f.close()
while os.path.exists("myfile.%d" % os.getpid() ):
  doSomething()

Then to terminate the script just remove the myfile.xxx and the application should quit for you. You can use this even with multiple instances of the same script running at once if you only need to shut one down. And it tries to clean up after itself....


The best way is to rewrite the script so it doesn't use while True:.

Sadly, it's impossible to conjecture a good way to terminate this.

You could use the Linux signals.

You could use a timer and stop after a while.

You could have dostuff return a value and stop if the value is False.

You could check for a local file and stop if the file exists.

You could check an FTP site for a remote file and stop of the file exists.

You could check an HTTP web page for information that indicates if your loop should stop or not stop.

You could use OS-specific things like semaphores or shared memory.


I think the most elegant would be:

keep_running = true
while keep_running:
    dostufF()

and then dostuff() can set keep_running = false whenever in no longer wants to keep running, then the while loop ends, and everything cleans up nicely.

Tags:

Python