I have been trying for some time to get my Listener to work to exit my program, but the only way I have gotten it to work is a bad solution.
Here is the way I want to make it work:
def main():
thread2 = threading.Thread(target=printing, args=())
thread2.start()
with Listener(on_release=on_release) as listener:
listener.join()
def on_release(key):
if key == Key.esc:
return False
def printing():
while True:
print('foo bar')
time.sleep(2)
if not Listener.running:
break
main()
And this is the way I have gotten it to work:
def main():
with Listener(on_release=on_release) as listener:
printing(listener)
def on_release(key):
if key == Key.esc:
return False
def printing():
while True:
print('foo bar')
time.sleep(2)
if not Listener.running:
break
main()
The basic idea is to not have to use listener everywhere in my code, if I do this for larger projects since having esc exit the program is good.
I know I have to use threading but not how to use it. can someone point me to my problem and offer a solution?
I have looked at Handling the keyboard, but don't really understand what it is saying tbh. I want to use this cleaner method.
I don't know pynput
, but threading
little bit. Thread can have child thread, so you can start new thread in Listener
. Like this... I'd like to say that, but trap in here. Even if parent thread dies, child thread is still alive! This thread is called zombie thread. Then what should we do? Answer is daemon thread. Daemon thread dies if alive threads are only daemon threads. To set child thread as a daemon thread, so parent thread dies together. Explain was so long, but go ahead:
def main():
with Listener(on_release=on_release) as listener:
thread2 = threading.Thread(target=printing, args=(), daemon=True)
thread2.start()
listener.join()
def on_release(key):
if key == Key.esc:
return False
def printing():
while True:
print('foo bar')
time.sleep(2)
if __main__ == '__main__':
main()
It will work!