简体   繁体   中英

Terminate background python script nicely

I am running a python script in the background using the command python script.py & . The script might look like this.

import time

def loop():
    while True:
        time.sleep(1)

if __name__=='__main__':
    try:
        loop()
    except KeyboardInterrupt:
        print("Terminated properly")

When it comes to terminating the script, I would like to do some cleanup before it is stopped (such as printing "Terminated properly"). If I run as a current process, this would be handled by the except statement after a keyboard interrupt.

Using the kill PID command means the cleanup is never executed. How can I stop a background process and execute some lines of code before it is terminated?

Use finally clause:

def loop():
    while True:
        time.sleep(1)

if __name__=='__main__':
    try:
        loop()
    except KeyboardInterrupt:
        print("Terminated properly")
    finally:
        print('executes always')

You can use signal module to catch any signals sent to your script via kill. You setup a signal handler to catch the signal in question that would perform the cleanup.

import signal
import time

running = 0

def loop ():
    global running
    running = 1
    while running:
        try: time.sleep(0.25)
        except KeyboardInterrupt: break
    print "Ended nicely!"

def cleanup (signumber, stackframe):
    global running
    running = 0

signal.signal(signal.SIGABRT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGQUIT, cleanup)
loop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM