2

I am using the pynput module and I want to restart a listener after a specific rule - condition - key combination is fulfilled.

The code I have written is shown below :

from pynput.keyboard import Key, Listener
from langdetect import detect
from pynput import keyboard

def listener_manager():
    #the idea is to return a new listener when needed
    listener = keyboard.Listener(on_press=on_press)
    return listener

def on_press(key):
    global string
    global listener
    global controller
    
    if key == keyboard.Key.esc: #if button escape is pressed close the program
        listener.stop()
    elif key == keyboard.Key.space:
        print(string)
        string=""
    elif key == keyboard.Key.shift:
        listener.stop()
        controller = keyboard.Controller()
        listener = listener_manager()
        listener.start()
        print("New listener started")
    elif key== keyboard.Key.alt_l:
        listener.stop()
        controller = keyboard.Controller()
        listener = listener_manager()
        listener.start()
        print("Left alt pressed")
    else:
        string = ''.join([string,str(key).replace("'","")])


string=""

"""This is the beginning"""
controller = keyboard.Controller()
# Collect events until released

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

Basically, I want to restart the listener when shift or alt (OR when language is changed), but the code I wrote didn't really work.

ppel123
  • 83
  • 3
  • 10

1 Answers1

0

Would something like this not suffice:

listener.stop()
listener.start()

I've found in my own program that this works:

listener = keyboard.Listener(on_press=on_press)

Without using join works with the above code.