signals - Python - Polling a variable -


i change global variable in signal handler , poll in main program. value not change in main thread.

is there qualifier need use make volatile (like in java) variable?

here's program:

test.py

import time import signal  def debug():     closesession = false      def sigint_handler(signal, frame):         global closesession          print('breaking poll...')         closesession=true      signal.signal(signal.sigint, sigint_handler)      # start program...      while not closesession:         time.sleep(1)         print('polling... closesession = %r' % closesession)      print('exiting! bye.')     # sent 'quit' stdin of program  if __name__ == "__main__":     debug() 

sigint_handler() gets called whenever press ctrl + c new value of closesession not used in main thread.

i following output:

$ python test.py
polling... closesession = false
polling... closesession = false

i press ctrl + c

^cbreaking poll...
polling... closesession = false

press ctrl + c, again

^cbreaking poll...
polling... closesession = false

press ctrl + c, again

^cbreaking poll...
polling... closesession = false
polling... closesession = false

the problem scope.

inside debug() function, didn't declare closesession global, means have 2 variables called closesession. 1 global , 1 scoped within debug() function. , inside sigint_handler() function, you've explicitly instructed use global one, shadowed scoped 1 in outer function.

you can solve declaring global before assignment in debug():

def debug():     global closesession     closesession = false     ... 

by way, code not work on windows, throws ioerror because sleep function interrupted. workaround worked me is:

... while not closesession:     try:         time.sleep(1)     except ioerror:         pass     print('polling... closesession = %r' % closesession) ... 

it's not pretty works.


Comments