Using variables in signal handler - require global?

后端 未结 5 1902
不思量自难忘°
不思量自难忘° 2021-01-01 10:10

I have a signal handler to handle ctrl-c interrupt. If in the signal handler I want to read a variable set in my main script, is there an alternative to using a \"global\" s

5条回答
  •  不知归路
    2021-01-01 11:02

    You can use a closure as the signal handler that acquires its state from the main script:

    import signal
    import sys
    import time
    
    def main_function():
    
        data_for_signal_handler = 10
    
        def signal_handler(*args):
            print data_for_signal_handler
            sys.exit()
    
        signal.signal(signal.SIGINT, signal_handler) # Or whatever signal
    
        while True:
            data_for_signal_handler += 1
            time.sleep(0.5)
    
    if __name__ == '__main__':
        main_function()
    

提交回复
热议问题