3

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.

m100psi
  • 43
  • 3

1 Answers1

1

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
kindall
  • 178,883
  • 35
  • 278
  • 309