This is a sleeping service,

import time
bufsize = 0
f = open("/home/user/sleep-log", "w", bufsize)
  f.write("going for a deep sleep......")
  time.sleep( 1000000000)
  import traceback; f.write(traceback.format_exc())
  f.write("that is surprising.. final block just ran")

And i have a ubuntu upstart task to run this,

description "sleeper"
author "saravana"
start on runlevel [2345]
stop on runlevel [!2345]
  exec /usr/bin/python /home/user/a.py
end script

When i do,

service  sleeper start
service sleeper stop

the log file contains,

going for a deep sleep.......

Finally block is skipped. How can i ensure my cleanup code will always run? I can do it in conf file using post stop script but for legacy reasons, i want to do it inside python file.


When Upstart stops a job it sends the SIGTERM signal. By default SIGTERM causes the program to immediately exit. This means the execution does not flow through the rest of your code, it simply stops.

A signal handler can be implemented using the signal module, you can find details on it's usage here. This will allow you to run code upon receiving the signal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.