Python: Return of a specific function

Asked

Viewed 48 times

-1

How can I access the function’s Return on_press(key)?

The program below captures keystrokes. Open, for example, the notepad and type test and teclhe Enter

The result in the list should be: lista = ['t','e','s','t','e','<key.esc>']

Can you give me a hint? Thanks.

from pynput import keyboard


def on_press(key):
    lista = []
    try:
        texto = '{0}'.format(key.char)
        lista.append(texto)
    except AttributeError:
        texto = '<{0}>'.format(key)
        lista.append(texto)
    return lista

def on_release(key):
    if key == keyboard.Key.esc:
        # Stop listener
        return False


# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()
  • 1

    Why don’t you leave the variable lista in the overall scope?

  • I was making a mistake. I had tried. Well, the answer from the colleague below worked and even accepted (it worked) in putting the variable in the global scope.

1 answer

1


You can either use a global variable or a class. Personally I prefer the idea of a class:

from pynput.keyboard import Key, Listener


class Keyload():
    def __init__(self):
        self.lista = []
        with Listener(
                on_press=self.on_press,
                on_release=self.on_release) as listener:
            listener.join()

    def on_press(self,key):
        print('{0} pressed'.format(key))
        self.lista.append('{0}'.format(key))

    def on_release(self,key):
        if key == Key.esc:
            # Stop listener
            return False

dados = Keyload()
print(dados.lista)

But if you still prefer to use a global variable:

from pynput.keyboard import Key, Listener

global lista

def on_press(key):
    print('{0} pressed'.format(key))
    lista.append('{0}'.format(key))

def on_release(key):
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
lista = []
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

print(lista)
  • I had tried to put the variable in the global scope but was giving error. But now it worked. But the best idea is to use the same class. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.