terminate a program gracefully from a thread

Jabba Laci jabba.laci at gmail.com
Sat Mar 22 08:40:31 EDT 2014


Hi,

I have a script (see below) that I want to terminate after X seconds.
The main loop of the program is waiting for user input.
The program enters the main loop and I try to shut down the program
after X seconds from a thread but I can't figure out how to do it. The
program should also do some cleanup before termination, so the shut
down must be graceful.

The code below is a simplified version. The whole idea is the
following: I have a script that has grown quite big over time. It
needs to read several data files, so when I start it for the first
time, it takes about 3-4 seconds to launch. The next start is much
faster since, I guess, the OS has done some caching. I use this script
a lot and the first slow launch bothers me. My idea: after booting, I
want to start the script in the background in suicide mode. OS does
the caching, so when I need it, it starts quickly.

See the code below with comments.

Thanks,

Laszlo

===============

import atexit
import sys
import time
from threading import Thread
import os

def suicide(wait):
    time.sleep(wait)
    print("should exit now...")
    sys.exit()      # exits this thread but not the main thread
#    os._exit(0)    # no cleanup with this :(

def cleanup():
    # I want it to run before termination.
    print("cleaning up...")

def main():
    Thread(target=suicide, kwargs={'wait': 3}).start()
    #
    while True:
        try:
            inp = raw_input("in> ")
            print(inp)
        except (KeyboardInterrupt, EOFError):
            print()
            sys.exit()

#####

if __name__ == "__main__":
    atexit.register(cleanup)
    main()



More information about the Python-list mailing list