0

I am trying to make a program that prints 'hi' until the user releases a key. My current code still runs even after a key release. I'm pretty sure it's because the keyboard listener is on another thread, but I don't know how to run on that thread.

from pynput.mouse import Button, Controller
from pynput import keyboard

running = True

def on_release(key):
  running = False

listener = keyboard.Listener(
    on_release=on_release)
listener.start()

while running:
  print("hi")

Putting it in a class yields the same results

class Clicker():
  def __init__(self):
    self.running = True
    self.listener = keyboard.Listener(on_release=self.on_release)
    self.listener.start()

  def on_release(self):
    self.running = False
    print("Stopped")

  def run(self):
    while(self.running):
      print("hi")

1 Answers1

0

Global keyword required to modify global variables

Because running is defined as a global variable, the method on_release() will not be able to modify it unless you use the global keyword. The best reference I can find from the official documentation is here.

Example

Global variable not modified:

global_variable = 1

def change_global_variable_wrong():
  global_variable = 2 # This statement declares a new local variable
                      # called `global_variable` and assigns the 
                      # value `2` to it.

change_global_variable_wrong()

print(global_variable) # prints 1

Global variable is modified:

global_variable = 1

def change_global_variable_correct():
  global global_variable
  global_variable = 2

change_global_variable_correct()

print(global_variable) # prints 2

Relevant code snippet

The relevant change required for your code would be along the lines of the following:

def on_release(key):
  global running
  running = False
yongjieyongjie
  • 813
  • 10
  • 18