BaseHTTPServer socket close after python script exit

389 views Asked by At

I already searched for solutions to my questions and found some, but they don't work for me or are very complicated for what I want to achieve.

I have a python (2.7) script that creates 3 BaseHTTPServers using threads. I now want to be able to close the python script from itself and restart it. For this, I create an extra file called "restart_script" with this content:

sleep 2
python2 myScript.py

I then start this script and after that, close my own python script:

os.system("nohup bash restart_script & ")
exit()

This works quite well, the python script closes and the new one pops up 2 seconds later, but the BaseHTTPServers do not come up, the report that the Address is already in use. (socket.error Errno 98).

I initiate the server with:

httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)

Then I let it serve forever:

thread.start_new_thread(httpd.serve_forever, tuple())

I alternatively tried this:

httpd_thread = threading.Thread(target=httpd.serve_forever)
httpd_thread.daemon = True
httpd_thread.start()

But this has the same result.

If I kill the script using strg+c and then start it right again right after that, everything works fine. I think as long as I want to restart the script from its own, the old process is still somehow active and I need to somehow disown it so that the sockets can be cleared.

I am running on Linux (Xubuntu).

How can I really really kill my own script and then bring it up again seconds later so that all sockets are closed?

1

There are 1 answers

0
Michael On

I found an answer to my specific problem.

I just use another script which starts my main program using os.system(). If the script wants to restart, I just close it regularly and the other script just starts it again, over and over...

If I want to actually close my script, I add a file and check in the other script if this file exists..

The restart-helper-script looks like this:

import os, time

cwd = os.getcwd()

#first start --> remove shutdown:
try:
    os.remove(os.path.join(cwd, "shutdown"))
except:
    pass

while True:
    #check if shutdown requested:
    if os.path.exists(os.path.join(cwd, "shutdown")):
        break
    #else start script:
    os.system("python2 myMainScript.py")
    #after it is done, wait 2 seconds: (just to make sure sockets are closed.. might be optional)
    time.sleep(2)