1 year ago

#219954

test-img

Lan Do

Python signal handler weird behavior

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?

python

multithreading

signal-handling

0 Answers

Your Answer

Accepted video resources