Using variables in signal handler - require global?

后端 未结 5 1852
不思量自难忘°
不思量自难忘° 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:04

    Within the object-oriented paradigm (OOP) it's quite convenient to use lambdas for that purpose. Using lambdas you could pass some additional context (like a self reference) and/or get rid of the unused arguments (signal, frame).

    import time
    import signal
    
    class Application:
    
        def __init__( self ):
            signal.signal( signal.SIGINT, lambda signal, frame: self._signal_handler() )
            self.terminated = False
    
        def _signal_handler( self ):
            self.terminated = True
    
        def MainLoop( self ):        
            while not self.terminated:
                print( "I'm just doing my job like everyone else" )
                time.sleep( 3 )
    
    app = Application()
    app.MainLoop()
    
    print( "The app is terminated, exiting ..." )
    

提交回复
热议问题