简体   繁体   中英

How to run a command before stopping a python script

I have a python code which start a UDP communication on a port 5002 . So what happens is when I first run the code, it works normally then I close the python script using ctlr z/ctrl c and then again run the code it shows me below error:

sock.bind(address)
OSError: [Errno 98] Address already in use

This may be because the python script is running and keeping the port busy. So it shows me the above error. To resolve this, I thought of running these two commands right before the code kills sock.close() to close the socket and sys.exit() to exit the python script properly. Thats why I need to know how can I run these commands right before the code is killed. I cannot use KeyboardInterrupt exception because in future this will be running as a service.

I found this answer but not able to implement it. For example, if I do:

import atexit
import time

def exit_handler():
    print("STOPPED")

while True:
    print("Running....")
    time.sleep(1)
    atexit.register(exit_handler)

This keeps on running but when I kill the code it doesn't print Stopped . How to implement it or is there any alternative way of handling my situation.

Thanks

The documentation of atexit module has an important note:

Note: The functions registered via this module are not called when the program is killed by a signal not handled by Python

That means that if you kill the script without special processing, the registered functions will not be called.

So you should instead register handlers for SIGTERM and SIGINT:

signal.signal(SIGTERM, (lambda signum, frame: exit_handler()))
signal.signal(SIGINT, (lambda signum, frame: exit_handler()))

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