How to stop an infinite loop safely in Python?

后端 未结 4 1965
长发绾君心
长发绾君心 2020-12-09 11:00

I\'ve got a script that runs on a infinite loop and adds things to a database and does things that I can\'t just stop halfway through so I can\'t just press ctrl+C and stop

4条回答
  •  爱一瞬间的悲伤
    2020-12-09 11:04

    the below logic will help you do this,

    import signal
    import sys
    import time
    
    run = True
    
    def signal_handler(signal, frame):
        global run
        print "exiting"
        run = False
    
    signal.signal(signal.SIGINT, signal_handler)
    while run:
        print "hi"
        time.sleep(1)
        # do anything
        print "bye"
    

    while running this, try pressing CTRL+C

提交回复
热议问题