Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graceful exiting of a program in Python?

Tags:

python

I have a script that runs as a

while True:
  doStuff()

What is the best way to communicate with this script if I need to stop it but I don't want to kill it if it is in the middle of an operation?

like image 650
James Avatar asked Jan 20 '10 22:01

James


2 Answers

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....

like image 146
Michael Anderson Avatar answered Sep 28 '22 10:09

Michael Anderson


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.

like image 25
S.Lott Avatar answered Sep 28 '22 10:09

S.Lott