from pynput.keyboard import * def press_on(key) : print ('press ON: {}'.format(key)) def press_off(key) : print ('press OFF: {}'.format(key)) if key== key.esc: return false with Listener (on_press, on_release = press_off) as listener: listener.join()