Ming
Ming

Reputation: 1612

python pynput handling keyboard

i trying make one keyboard handle with this context:

listener de keyboard and when f1 is pressed start ( press and release this keys: q w e ) and when f2 is pressed set the status to false for stoping the key press( q w e):

from pynput.keyboard import Key, Listener

STATUS = True

def on_release(key):
    if key == Key.f1:
        # Stop listener
        STATUS = False
    if key == key.f2:
        STATUS = True

def main():
    with Listener(
        on_release=on_release) as listener:
            listener.join()
    while STATUS:
        keyboard.press('q')
        keyboard.release('q')
        keyboard.press('w')
        keyboard.release('w')
        keyboard.press('w')
        keyboard.release('w')

and i got this error when run:

raceback (most recent call last):
  File "ap.py", line 1, in <module>
    from pynput.keyboard import Key, Listener
  File "/usr/local/lib/python3.8/dist-packages/pynput/__init__.py", line 40, in <module>
    from . import keyboard
  File "/usr/local/lib/python3.8/dist-packages/pynput/keyboard/__init__.py", line 31, in <module>
    backend = backend(__name__)
  File "/usr/local/lib/python3.8/dist-packages/pynput/_util/__init__.py", line 76, in backend
    raise ImportError('this platform is not supported: {}'.format(
ImportError: this platform is not supported: ('failed to acquire X connection: Bad display name ""', DisplayNameError(''))

Try one of the following resolutions:

 * Please make sure that you have an X server running, and that the DISPLAY environment variable is set correctly

edit

i already used pip3 install pynput

Upvotes: 1

Views: 443

Answers (1)

Jorge Granados
Jorge Granados

Reputation: 859

Before run the script try to connect to X server using this command

xhost +

For example create a bash script (script.bash) like this

DISPLAY=:0
xhost +
python3 yourscript.py

The run as

bash script.bash

Upvotes: 0

Related Questions