0

As far as I know, the signal handler in Python is executed in main thread, so I try the following script:

import signal, time
from threading import Event

def main():
        running = True
        event = Event()

        def handler(signal, frame):
                print("Value of event: %s" % event.is_set())
                print("Value of running: %s" % running)
                event.set()
                running = False

        signal.signal(signal.SIGINT, handler)
        while running:
                time.sleep(10)

if __name__ == '__main__':
        main()

After starting the program, I type Ctrl+C then the program raises the exception:

UnboundLocalError: local variable 'running' referenced before assignment

As soon as I remove the line:

running = False

the program works fine. The value of event is False for the first Ctr-C then True for next times as expected.

So what is the problem of the code and the underlining mechanism of the handler when procesing basic type vs object?

Lan Do
  • 63
  • 6
  • Your `running` in main (the one that == True) and `running` in handler (False one) are 2 different variables. If you don't add the line `running = False` it tries to get it from outside of its scope, so it takes the one from main. If you DO define it, you get an error because first you are trying to print and only then you define local variable `running`. – matszwecja Feb 24 '22 at 10:01
  • Both `running` and `event` are in the main() function, one is a basic-type value, one is an object, and the object works fine when referred. So why Python treats them differently in this case? – Lan Do Feb 25 '22 at 05:05
  • Instead of answering the question the mod marks this one as duplicated. Is he/she to lazy to understand what I'm actually trying to ask? – Lan Do Feb 25 '22 at 05:22

0 Answers0