Python - endless loop of script running in background + reload

I would like to have a python script that runs in the background (infinite loop).

def main():
    # inizialize and start threads
    [...]

    try:
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        my.cleanup()

if __name__ == '__main__':
    main()
    my.cleanup()
  • So that the application runs continuously in an endless loop, what is the best way? I want to delete time.sleep(1), which I do not need.

  • I would like to run a script in the background nohup python myscript.py &, is there any way to kill it “gracefully”? When I run it, usually press CTRL + C my.cleanup(), is there a way to invoke this when the kill command is used?

  • What if I want (using cron) to kill the script and restart it again? Is there any way to do this my.cleanup()?

thank

+4
source share
1 answer
  • , ? time.sleep(1), .

A while True while <condition> , .

A sleep() , , .

  1. script nohup python myscript.py ""? , CTRL + C, my.cleanup(), , kill?

, "" signal() "signal".

, :

import time
import signal

# determines if the loop is running
running = True

def cleanup():
  print "Cleaning up ..."

def main():
  global running

  # add a hook for TERM (15) and INT (2)
  signal.signal(signal.SIGTERM, _handle_signal)
  signal.signal(signal.SIGINT, _handle_signal)

  # is True by default - will be set False on signal
  while running:
    time.sleep(1)

# when receiving a signal ...
def _handle_signal(signal, frame):
  global running

  # mark the loop stopped
  running = False
  # cleanup
  cleanup()

if __name__ == '__main__':
  main()

, SIGKILL, , , . ( ).

, , , .

  1. , ( cron) script ? my.cleanup()?

cronjob , SIGKILL, , .

, -: , "" - , ( SIGHUP , ). , .

+4

All Articles