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