Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access local variables while handling ctrl-C event?

I wondered if it is possible to access variables local to the function running at the time ctrl-C interrupts the flow. Example, where main() is running when ctrl-C is pressed:

def main(myInfo):
    signal.signal(signal.SIGINT, KeyboardBreak)
    reportOut(myInfo)

def KeyboardBreak(signum, frame):
    reportOut(myInfo)

def reportOut(myInfo):
    print myInfo

I would like reportOut() to run whether main() gets all the way down to where it calls reportOut(), or the flow is interrupted.

like image 857
m100psi Avatar asked Dec 17 '25 05:12

m100psi


1 Answers

Your signal handler needs access to the variable myInfo. The easiest way to do this is to define KeyboardBreak() inside main() so that it has access to myInfo via closure.

def main(myInfo):

    def KeyboardBreak(signum, frame):
        reportOut(myInfo)

    signal.signal(signal.SIGINT, KeyboardBreak)
    reportOut(myInfo)

def reportOut(myInfo):
    print myInfo

Alternatively, you can write a factory function that creates your signal handler, again using a closure to hold myInfo. This approach is probably best when either of these functions is complex.

def main(myInfo):
    signal.signal(signal.SIGINT, KeyboardBreakFactory(myinfo))
    reportOut(myInfo)

def KeyboardBreakFactory(myinfo):

    def KeyboardBreak(signum, frame):
        reportOut(myInfo)

    return KeyboardBreak

def reportOut(myInfo):
    print myInfo
like image 119
kindall Avatar answered Dec 19 '25 21:12

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!