Display_Here Display_Here - 6 months ago 14
Python Question

Restarting a python program during sleep safely?

I have a python program that needs to run 24/7. It's asleep about 10% of the time in 30 second intervals. Is there a way to have the program stop and start again safely so that the restart is only during the sleep?

Here is a sample of the code, the

main()
function and implementation:

# =============================================================================
# MAIN
# =============================================================================

def main():
while True:
checkReply = Reply()
checkReply.time_to_reply()
checkReply.search_db()
time.sleep(10)


# =============================================================================
# RUNNER
# =============================================================================
print "start"
if __name__ == '__main__':
main()

Answer

One way would be to change your main() to something like this:

def main():
    restart_file = config.get('some_section', 'restart_file')
    while True:
        checkReply = Reply()
        checkReply.time_to_reply()
        checkReply.search_db()
        time.sleep(10)
        if os.path.exists(restart_file):
            os.unlink(restart_file)
            if 0 == os.fork():
                os.execl(shlex.split('command to run the updated program'))
            sys.exit('restarting')

For added credit use something like https://pypi.python.org/pypi/python-daemon/ to make your program daemonize itself at startup.

Then, to restart your program at its next sleep, all you have to do is touch the restart file. You can set its path to whatever you like in your configuration file.

Comments