Giter VIP home page Giter VIP logo

pynput's People

Contributors

albertz avatar amund211 avatar asweigart avatar bdrung avatar conflictious avatar daveatkinson avatar glandos avatar gpongelli avatar haoflynet avatar ma03lish avatar moses-palmer avatar munsuri avatar p403n1x87 avatar pfps avatar pklaus avatar tbm avatar vpoulailleau avatar yemreak avatar ylz-at avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pynput's Issues

A way to stop event propagation?

I've been writing a sort-of window manager, and I use a certain shortcut to move windows (Ctrl+Alt+mouse middle click).

I've got handling written for this working fine. However, I'd like to not propagate the middle click there, since that will interact with the window.
Is there any way to not pass events on?

In pyHook it can be done by just returning False in a mouse handler.

Issues to import lib pynput

hi guy i'm issue to import lib pynput in my linux, my issue pass to use basic code our site.
My python version is 3.5.2

from pynput.keyboard import Key, Listener


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


def on_release(key):
    print('{0} release'.format(key))
    if key == Key.esc:
        # Stop listener
        return False

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

The problem is:

/usr/bin/python3.5 /home/zirou/hk/programacao/python/python_3.5/mouseclick/pynput.py
Traceback (most recent call last):
  File "/home/zirou/hk/programacao/python/python_3.5/mouseclick/pynput.py", line 1, in <module>
    from pynput.keyboard import Key, Listener
  File "/home/zirou/hk/programacao/python/python_3.5/mouseclick/pynput.py", line 1, in <module>
    from pynput.keyboard import Key, Listener
ImportError: No module named 'pynput.keyboard'; 'pynput' is not a package

If you can help me I will be grateful, thank you
sorry my english.

Events based on selection?

I was wondering if it is possible to get an event like "text selected keyboard/mouse button released"?
That is, the moment with e.g. Shift+arrow buttons released or after selecting text with the mouse, the mouse being released.

Any idea how to achieve it?

BTW: this is really fantastic!

Exception raised when pressing numbers on keyboard

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-81-695b20117412> in <module>()
----> 1 k.press("1")

/home/adam/.local/lib64/python3.6/site-packages/pynput/keyboard/_base.py in press(self, key)
    369 
    370         try:
--> 371             self._handle(resolved, True)
    372         except self.InvalidKeyException:
    373             if resolved != original:

/home/adam/.local/lib64/python3.6/site-packages/pynput/keyboard/_xorg.py in _handle(self, key, is_press)
    211             try:
    212                 keycode, shift_state = self.keyboard_mapping[keysym]
--> 213                 self._send_key(event, keycode, shift_state)
    214 
    215             except KeyError:

/home/adam/.local/lib64/python3.6/site-packages/pynput/keyboard/_xorg.py in _send_key(self, event, keycode, shift_state)
    249         with display_manager(self._display) as dm, self.modifiers as modifiers:
    250             window = dm.get_input_focus().focus
--> 251             window.send_event(event(
    252                 detail=keycode,
    253                 state=shift_state | self._shift_mask(modifiers),

AttributeError: 'int' object has no attribute 'send_event'

pynput version: 1.3.5
python version: 3.6.1

To reproduce:

from pynput.keyboard import Controller
k = Controller()
k.press("1")

Fantastic library!

I'm using it in combination with my webcam to make my eyes move the mouse ^^

KeyError: undefined character name 'COMBINING DEGREE SIGN'

Pynput gives me an error when I try to convert L° into L̥:
KeyError: "undefined character name 'COMBINING DEGREE SIGN'"

I think it is somwhere in init.py, six.py, _win32.py, or _base.py.

The line in question seems to be:
'COMBINING ' + unicodedata.name(self.char))

It should be COMBINING RING, not COMBINING DEGREE SIGN.

Remembers ctrl and shift after release

Good day, thanks for creating this great library.

Python 2.7, release 1.1 of pynput, Windows 10

I am experiencing an odd issue with the keyboard monitor and control/shift keys.

On release of the control or shift key, the application remembers the key and the next input logged is then a special character.
For example

  • if I press 'a' and release, keyboard monitor logs a u'a'
  • if I press 'left control' and release, keyboard monitor logs a 'Key.ctrl_l'
  • if I then press 'a' and release, keyboard monitor logs a u'\x01'
  • if I then press 'a' and release again, keyboard monitor logs a u'a'

A similar thing is observed with the shift key. A capital 'A' is recognized on press of 'a' (without the shift). This means that the key press logged after a control or shift press and release is incorrect.

Not sure if this is in fact a pynput issue.

Regards

Problem to make work in Raspberry Pi (Python 2.7.9)

Hello, I was looking a package to get keypresses from the user for my Raspberry Pi (the last august release) project, and I found this package. I don't understand too much about python packages installation, but I proceed in this way:

"sudo pip install pynput"

In my code, I just inserted on the top "import pynput", and I started having trouble.

First I got errors of missing the "six" package, so I did:

"sudo pip install --upgrade six"

The --upgrade was needed. But now, I have a new problem:

"Traceback (most recent call last):
File "pdaGraphics.py", line 8, in
import pynput
File "/usr/local/lib/python2.7/dist-packages/pynput/init.py", line 23, in
from . import keyboard
File "/usr/local/lib/python2.7/dist-packages/pynput/keyboard/init.py", line 49, in
from ._xorg import KeyCode, Key, Controller, Listener
File "/usr/local/lib/python2.7/dist-packages/pynput/keyboard/_xorg.py", line 38, in
from pynput._util.xorg import (
File "/usr/local/lib/python2.7/dist-packages/pynput/_util/xorg.py", line 38, in
_check()
File "/usr/local/lib/python2.7/dist-packages/pynput/_util/xorg.py", line 36, in _check
display = Xlib.display.Display()
File "/usr/local/lib/python2.7/dist-packages/Xlib/display.py", line 127, in init
mod.init(self, info)
File "/usr/local/lib/python2.7/dist-packages/Xlib/ext/xinput.py", line 652, in init
disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData)
File "/usr/local/lib/python2.7/dist-packages/Xlib/display.py", line 227, in getattr
raise AttributeError(attr)
AttributeError: ge_add_event_data"

I don't know what to do here.
Already tried some commands like "sudo apt-get install python-xlib", but still no results.

ctrl+x doesn't "cut" (copy) but only print ^X in the console

following pynput documentation I tried this to "cut":

1: I did select some text in an editor

2: run this_code.py using a shortcut (without leaving the active windows)

from pynput.keyboard import Key, Controller
keyboard = Controller()
with keyboard.pressed(Key.ctrl):
    keyboard.press('x')
    keyboard.release('x')

The python console open actually print: ^X. The combination of keys are right but it doesn't do what it's suppose to do: cut the selected text store it in the clipboard. (I'm not interested to just store the clipboard content in a variable, I just need the code to acte like Ctrl+C does)

I guess this answer will also solve the remaining part: Ctrl+V (to past some data which will be first inserted in the clipboard)

Context manager Keyboard.pressed not releasing keys

This sample code from your documentation doesn't work:

with Keyboard.pressed(Key.shift):
    Keyboard.press('a')
    Keyboard.release('a')

An an "a" is emitted instead of "A".

Changing the last line of the pressed method fromself.press(key) to self.release(key) is probably the intended behaviour.

Thanks for the library.

Cheers, Toby

String representation includes quotes.

I copied your example code on Monitoring the keyboard into a file called pynput_listener.py and ran it with Python 3.5 on Ubuntu Linux. I get the following output:

$ python3 pynput_listener.py
'a' pressed
a'a' release
'b' pressed
b'b' release
'c' pressed
c'c' release
Key.esc pressed
^[Key.esc release

The line of code print('{0} pressed'.format(key)) is returning a string with two embedded quote characters.

Similarly, if I change those lines to just print(str(key)) I get:

$ python3 pynput_listener.py
'a'
a'a'
'b'
b'b'
'c'
c'c'
Key.esc
^[Key.esc

Shouldn't str(key) return a single character string, and not a 3-character string, that includes quotes?

the input string be sent as command into the terminal make unexpected behavior

Hi,
I want a menu which can interact with the keyboard as an input method. Something like the code bellow.

The problem is, it also sends the input string as a command into the terminal make unexpected behavior.
For example:

  • the input='start', the 'start' command also be sent to the keyboard, causes new command window display.
  • the input='exit', the 'exit' command also be sent to the keyboard, causes the current command window terminated.

So, how can I prevent such input directly send to the keyboard?
Thank you

from pynput import keyboard
keys=[]
#TODO: it also send the input string as command into the terminal made unexpected behavior

def on_press(key):
try:
keys.append(key.char)
except:
pass

def on_release(key):
if key == keyboard.Key.enter:
str = ''.join(keys)
keys[:] = []
if str == "start":
# do something with start command
print(str)
if str == "stop":
# do something with stop command
print(str)
if str == "exit":
# exit
return False

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

AltGr is split in Key.ctrl_l and Key.alt_r

I want to turn AltGr+P into ¶ (PILCROW SIGN):
if key == 'P':
if keyboard.alt_gr_pressed:
keyboard.type('\b''¶')
But somehow I didn't manage.

When testing why, I realized that when I type the physical AltGr key alone, it gives me back
key Key.ctrl_l released
key Key.alt_r released
Is that normal?

Pynput "Return" key not sent when using Discord

Hello, I've recently run in to a strange problem when using pynput. When listening to the keyboard on my machine whenever I open Discord (https://discordapp.com/) desktop application (and some other apps) and type a message - then press "Enter" the key is never sent? I've actually just gotten the "enter" key to send closing out of some background applications, so my assumption is this is due to some kind of computer stress?

I noticed if I spam the key it'll go through as well, and pynput still captures it regardless. If this isn't a pynput issue or there's something I'm missing I apologize.

Intercepting keystrokes without forwarding them

Hello there

I'm trying to build a basic "remapper" that takes keyboard input and relays it differently based on modes/chords or other variables.

While I mostly have a system in place which can read keystrokes and interpret them (works well so far) I haven't been able to disable the keystrokes for other purposes. i.e: If I get the keystroke for A, I can't prevent the OS from forwarding that A keystroke to the window in focus even though my program may want to send the keystroke for B or Tab or anything else.

I wonder if there's a way to make this work at least in macOS. I know that the Plover project is written in Python, and it might have the answers. I'm not so good with this stuff unfortunately so I can't really tell, but I think here's how Plover does it on macOS as well as Windows.

Would appreciate any hints.

Thanks
Adi Ron.

Crashing on mouse press

Hello, loving the library so far.

I set up a basic mouse listener (straight from your example code), and on button press my program is crashing. I tried to debug myself, but I think there is something I'm not understanding.

For reference, I am using MBP 13.3 inch with no Touch Bar, and python 2.7.

Here is the code I am using:

   20 def on_click(x, y, button, pressed):
   19     print(button) # identify which button was pressed
   18     print(pressed)
<...>
    5 # Collect events until released
    4 with mouse.Listener(
    3         on_move=on_move,
    2         on_click=on_click,
    1         on_scroll=on_scroll) as listener:
  46      listener.join()

As you can see, this is very basic code. And here is the error:

Traceback (most recent call last):
  File "mouse_monitor.py", line 46, in <module>
    listener.join()
  File "/usr/local/lib/python2.7/site-packages/pynput/_util/__init__.py", line 185, in join
    six.reraise(exc_type, exc_value, exc_traceback)
  File "/usr/local/lib/python2.7/site-packages/pynput/_util/__init__.py", line 140, in inner
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/pynput/_util/darwin.py", line 246, in _handler
    self._handle(proxy, event_type, event, refcon)
  File "/usr/local/lib/python2.7/site-packages/pynput/mouse/_darwin.py", line 201, in _handle
    (press, release, drag), _ = button.value
TypeError: 'NoneType' object is not iterable

This error occurs when I perform any type of button click using the mouse.

The mouse movement and scrolling features are working just fine - I can collect all data from that. Only mouse clicks seem to prove an issue.

Thank you!

Access keyboard Unicode characters

Hi,
I want to detect Unicode characters from keyboard events. I tried the simple example of your code but the problem is if I change my input language from EN to another Unicode language like Spanish or Arabic it still shows the old characters and I need to rerun my script. I tried this simple code to detect Alt+Shift and reload the module to take effect but no luck.

import pynput
from importlib import reload

# The key combination to check
COMBINATION = {pynput.keyboard.Key.shift, pynput.keyboard.Key.alt_l}

# The currently active modifiers
current = set()

def on_press(key):
    print("current key is: ",key)
    if key in COMBINATION:
        current.add(key)
        if all(k in current for k in COMBINATION):
            print('All modifiers active!')
            listener.stop()

def on_release(key):
    try:
        current.remove(key)
    except KeyError:
        pass

with pynput.keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

print("Done")
reload(pynput)
import pynput as pynput2

def on_press2(key2):
    print("current key2 is: ",key2)


with pynput2.keyboard.Listener(on_press=on_press2) as listener:
    listener.join()

Thanks.

Bad display name "" when running via ssh

Hi,

I'm trying to use this package to control a Raspberry Pi to drive an RC car from my laptop via wifi. Is it possible to use this package to capture key strokes from my laptop while running the script on the Pi via ssh?
The script with pynput works great when I run directly from the Pi.

Thanks

Traceback (most recent call last):
  File "keycontrol.py", line 28, in <module>
    from pynput.keyboard import Key, Listener, KeyCode
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/pynput/__init__.py", line 23, in <module>
    from . import keyboard
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/pynput/keyboard/__init__.py", line 49, in <module>
    from ._xorg import KeyCode, Key, Controller, Listener
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/pynput/keyboard/_xorg.py", line 38, in <module>
    from pynput._util.xorg import (
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/pynput/_util/xorg.py", line 38, in <module>
    _check()
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/pynput/_util/xorg.py", line 36, in _check
    display = Xlib.display.Display()
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/Xlib/display.py", line 80, in __init__
    self.display = _BaseDisplay(display)
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/Xlib/display.py", line 62, in __init__
    display.Display.__init__(*(self, ) + args, **keys)
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/Xlib/protocol/display.py", line 53, in __init__
    name, host, displayno, screenno = connect.get_display(display)
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/Xlib/support/connect.py", line 62, in get_display
    return mod.get_display(display)
  File "/home/pi/code/donkey/env/lib/python3.4/site-packages/Xlib/support/unix_connect.py", line 47, in get_display
    raise error.DisplayNameError(display)
Xlib.error.DisplayNameError: Bad display name ""

How to detect key being held down instead of a press?

I am currently working on implementing a feature which "does something while a key is being held down".. As I understand pynput, it seems impossible to implement such feature? or am i missing something?

This implementation:

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.cmd_l:
        try:
            print('- Started recording -'.format(key))
        except IOError:
            print "Error"
    else:
        print('incorrect character {0}, press cmd_l'.format(key))


def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False


with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Only detect one press, also when the key is being held down.. It doesn't seem to read the stream..

I thought maybe the use of a while loop would help, also giving the way the problem is stated, so i tried this...

from pynput import keyboard

def on_press(key):
    while key == keyboard.Key.cmd_l:
        try:
            print('- Started recording -'.format(key))
        except IOError:
            print "Error"
    else:
        print('incorrect character {0}, press cmd_l'.format(key))


def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Which resulted in being stuck in a while loop.. and not come outside..
can the library be used like this, can it detect "a key being held down"?

Use internal keyboard state in the win32 keyboard listener

Rationale

Currently, pynput relies on the operating system keyboard state when translating scan codes to actual characters or keys. This has a number of advantages:

  • There is no need to maintain a keyboard state inside pynput
  • We can use ToUnicodeEx to translate key presses to actual unicode characters.

Unfortunately, it also brings a number of drawbacks:

  • ToUnicodeEx modifies a global keyboard buffer, leading to race conditions with other applications.
  • It requires applying some hacks, since the keyboard state is not fully updated when our system hook is called.
  • It is the main suspect for #15, #34 and #42

Suggested solution

We should use the output of MapVirtualKeyEx to update an internal keyboard state for each listener.

This will require some research into what the state actually should contain, and suitable methods to update it. The solution must be able to fully match the expected behaviour of a pynput keyboard listener, and respect the current keyboard layout.

Exception Handling

Hi,

Is there a way to do Try Catch Traceback in pynput. I have tried all sort of excepiont handling in on_click block or with listener: , but no avail.

Any hints please?

Pynput listeners causing system-wide input problems

Here is a minimal example program using pynput.

from pynput.keyboard import Listener
listener = Listener()
listener.start()
listener.join()

While this program is running, I experience some strange behavior with keyboard input.

1: I'm using a utility called "Steelseries Engine 3" version 3.9.6 to bind some of my mouse buttons to alt-left, alt-right, and ctrl-w. With pynput active in the background, about half of the time I press one of these buttons, the modifier key gets lost. So I sometimes get the letter "w" sent by itself instead of the ctrl-w shortcut combination. (tested in Chrome and notepad++)

2: Sometimes when I press enter, nothing happens. It seems to partially depend on what program has focus: Discord and Chrome usually have the problem, but Intellij doesn't. (they're using different ways of detecting input I guess?) I haven't exhaustively tested every key on the keyboard, but all the letters and punctuation appear to not have this problem.

These might even both be the same problem, just certain kinds of keystrokes being eaten by pynput, which can include ctrl and enter.

Both of these issues are inconsistent from one second to the next, but very consistent in the sense that over several seconds of trying to trigger the problem, the problem will occur. I've never had any problems remotely like this until I started working with pynput for a project.

System details:
Windows 8.1
Python 2.7.13 (was previously on 2.7.10, updated to see if it would fix this problem)
pynput 1.2

optionally block propagation of keyboard events

Hi,

I really like your module. It is very simple to use, and I'm using it to teach Python to middle-schoolers.

Currently, I am using this code as a demonstration (modified only slightly from your docs):

#!/usr/bin/env python
from pynput import keyboard
def on_press(key):
    try:
        print('Pressed: {}'.format(key.char))
    except AttributeError:
        print('Special key: {}'.format(key))

def on_release(key):
    print('Release: {}'.format(key))
    if key == keyboard.Key.esc:
        return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    while True:
        print(".")
        time.sleep(1.0)

It produces output like:

$ python test.py 
.
.
aPressed: a
Release: u'a'
.
jPressed: j
.
Release: u'j'
.

The problem is that each key event is propagated to the terminal, so it appears in addition to the messages.

When the program finishes, all of the output is again echoed to the bash prompt, like so:

$ ajadajjjajddjaajajajjajajajjajajajajj

Can you provide an optional flag or method that blocks propagation of keyboard events after they are handled by pynput? I want to use this for a simple game, and I want the game to respond to the keyboard as a controller. I do not want to see the keystrokes echoed to the terminal during the game or after the game.

Thanks!

1.3.3+ fails to install on Ubuntu

System: Ubuntu 14.04 / Python 2.7

Command to reproduce: pip install pynput

Error:

Collecting pynput
Using cached pynput-1.3.4-py2.py3-none-any.whl
Requirement already satisfied: six in /home/warnellg/anaconda2/lib/python2.7/site-packages (from pynput)
Collecting pyobjc-framework-Quartz>=3.0 (from pynput)
Using cached pyobjc-framework-Quartz-3.2.1.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-p6tKpe/pyobjc-framework-Quartz/setup.py", line 70, in <module>
[ 'Modules/_CVPixelBuffer.m' ]),
File "pyobjc_setup.py", line 375, in Extension
os_level = get_os_level()
File "pyobjc_setup.py", line 189, in get_os_level
pl = plistlib.readPlist('/System/Library/CoreServices/SystemVersion.plist')
File "/home/warnellg/anaconda2/lib/python2.7/plistlib.py", line 75, in readPlist
pathOrFile = open(pathOrFile)
IOError: [Errno 2] No such file or directory: '/System/Library/CoreServices/SystemVersion.plist'

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-p6tKpe/pyobjc-framework-Quartz/

Comments: Perhaps related to commit 4c0eb7e84c962059f6d53ef7aa202c5d6f00d330 ("merge branch fixup-dependencies'"), since pip now tries to install pyobjc on Ubuntu 14.04. Rolling back to 1.3.2 resolves this issue (ie, pip install pynput==1.3.2 succeeds).

keyboard init error

I just use following code to init a keyboard:

from pynput.keyboard import Key, Controller
keyboard = Controller()

but end up with errors in console:

File "/usr/local/lib/python3.6/site-packages/pynput/keyboard/_darwin.py", line 134, in __init__
    self._mapping = get_unicode_to_keycode_map()
  File "/usr/local/lib/python3.6/site-packages/pynput/_util/darwin.py", line 163, in get_unicode_to_keycode_map
    with keycode_context() as context:
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 82, in __enter__
    return next(self.gen)
  File "/usr/local/lib/python3.6/site-packages/pynput/_util/darwin.py", line 128, in keycode_context
    layout_data = layout.bytes().tobytes()
AttributeError: 'NoneType' object has no attribute 'bytes'

Why this happened?

Mouse handling does not work in latest master

I upgraded to latest master so I could try fix that other issue, and it is now unable to process any mouse input.

I ran the test suite, however everything failed.

errors

Running Windows 7, 64-bit.
My python install in that picture is 32-bit 2.7.10.

I tried both Python 2.7 and 3.5, both failing.
The tests work fine for the version currently on pypi.

deadkeys

The deadkeys are still not working 100% correctly, I think.

Let's say I want to turn `M into M̀ (a combined character).
But that does not function because there is no character M̀ (at least not in my keyboard layout), so the deadkey remains virtual, until I type a second character (which is ignored in the memory) and the deadkey appears on my screen together with the second character.

I don't know if there is a way to fix this.
What I want to have is the second character not being ignored in the memory.

Also, when I type the deadkey twice, while on my screen the characters are `` (down, down), they are ´` (up, down) in the memory.
I think that is odd...

Usage, manipulating mouse input

Hi,

I was wondering if someone would be able to help me with a problem I am facing.

The code below is meant to intercept the mouse input and translate it by a factor of 2.
However, it stops working after intercepting the first two on_move mouse events and locks up the mouse.
I suspect it is something to do with concurrency and the listener but am unsure.
Any help would be appreciated 😄

from pynput import mouse


class PassingMouseListenerException(Exception): pass


class Mouse:
    def __init__(self):
        self.control_display_gain = 2
        self.last_position = None
        self.mouse = mouse.Controller()

    def on_move(self, x, y):
        if self.last_position is None:
            self.last_position = (x, y)
        else:
            x_difference = (x - self.last_position[0]) * self.control_display_gain
            y_difference = (y - self.last_position[1]) * self.control_display_gain
            pos = (x_difference + self.last_position[0], y_difference + self.last_position[1])
            print("difference: {0}, {1}".format(x_difference, y_difference))
            print("old position: {0}, {1} captured position: {2}, {3} new position: {4}, {5}".format(self.last_position[0], self.last_position[1], x, y, pos[0], pos[1]))
            self.mouse.move(x_difference, y_difference)
            self.last_position = pos

    def on_click(self, x, y, button, pressed):
        print("I clicked")

    def on_scroll(self, x, y, dx, dy):
        pass

    def run(self):
        self.last_position = self.mouse.position
        with mouse.Listener(
                on_move=self.on_move,
                on_click=self.on_click,
                on_scroll=self.on_scroll) as listener:

            try:
                listener.join()
            except Exception as e:
                print("listener died: {}".format(e))

if __name__ == "__main__":
    program = Mouse()
    program.run()

how to send special keyboard event through subprocess.PIPE

Hi
i'm trying to build a music player that can control playing state(pause, resume, forward ...) with keyboard
i run a mplayer in a subprocess and try to send keyboard events with the help of pynput.keyboard
(my OS is ubuntu 16.04)
this is the code to start a mplayer in a subprocess

self.player_handler = subprocess.Popen(['mplayer', mp3_url],
                                                   stdin=subprocess.PIPE,
                                                   stdout=subprocess.PIPE,
                                                   stderr=subprocess.PIPE)

this is the keyboard listener code(only the on_press method here)

        def on_press(key):
            # print '{} pressed, capture by player listener.'.format(key)
            if self.is_player_alive and self.is_playing:
                if isinstance(key, Key):
                    if key == Key.right: # forward                       
                        self.player_handler.stdin.write(???)
                        self.player_handler.stdin.flush()                 

                elif isinstance(key, _xorg.KeyCode):
                    if key.char == u'p': # pause/resume
                        self.player_handler.stdin.write('p')
                        self.player_handler.stdin.flush()

note that mplayer itself has key p as pause and right arrow key as forward

now when the music is playing and i press button p, the press action is captured by the listener and the stdin.write('p') method writes the character 'p' into the subprocess, the mplayer in subprocess pauses the music as i expected

but what should i send to the subprocess to simulate the right key? does pynput support such function ? i have read some articles about keyboard events in linux but haven't been able to figure it out.

Thanks

How to listen Key combination?

Great library!

When I use the pynput I want to listen the key combination, Such as: ctrl+cmd

I can't find the way to do that,So I ask you for help.👻

Support for numeric keypad missing

At the moment keycodes that come from numeric keypad keys are ignored by pynput. Could you at them so there is no difference to alphanumeric digit keys?

Extra mouse buttons crash the click listener on Linux

I have a mouse with extra button on the side. When I click one of these buttons the listener crashes:

ValueError: 8 is not a valid Button

I'm pretty sure the error is that the Button enum class doesn't have a value for mouse button 8.

I was thinking the extra buttons 8 and 9 that I have on my mouse could be added to that enum, but it might be better to make it handle arbitrary buttons. If you have a preference, I can submit a PR with that change.

Pause listener while using Controller().type

When I type something programatically, the listener records what I type and more:

from pynput import keyboard

def on_release(key):
    print key

# type A1 when I press tab
def expander(msg, data):
    if data.vkCode == 0x9 and msg == 256:
        listener.suppress_event()
    elif data.vkCode == 0x9 and msg == 257:
        keyboard.Controller().type("A1")
        listener.suppress_event()

with keyboard.Listener(on_release=on_release, win32_event_filter=expander) as listener:
    listener.join()

Types "A1" in a text editor, but the listener gives:

u'A'
u'1'
u'\x00'
u'1'

Process finished with exit code 1

Is there a way to stop listening while I programmatically type something with pynput?

Auto detect key on mouse double clicks

Hi,
I have a strange problem I wrote a simple script to show the current key char or key name and I detect the ctrl+c function. It works fine if I press ctrl+c but when I double click on a file it accidentally detects the ctrl+c but I never pressed any key on my keyboard and only double click my mouse.
Here is the code I used:

from pynput import keyboard
from time import sleep
import pyperclip

def on_press(key):
    if key == keyboard.Key.esc:
        listener.stop()
    else:
        try:
            print("key.char", ord(key.char))
            if(ord(key.char) == 3):
                print("Ctrl+C Pressed!!!")
        except:
            print("key.name", key.name)

lis = keyboard.Listener(on_press=on_press)
print("start #1")
lis.start()
sleep(100)

I didn't use lis.join() because I'm creating an object from this code and don't want to make it block my code.

I am not sure if this problem relates to your library but is there any way to detect ctrl+c maybe it won't duplicate.
Thanks.

Pynput not receiving Shift modifier when using Microsoft Edge

Hello!

I'm writing an app that records the keyboard and mouse and allows the user to replay their actions based on what they've done.

I wanted to record my in Microsoft Edge because windows 10 comes with it by default. If I type:
"TestIng" anywhere in Edge it is recorded as:
"testing"

Meaning the shift modifier wasn't detected for some reason?

I cannot replicate this bug in a normal window like notepad.

No module named Xlib.display

Hi I had to run sudo to install the setup.py with python and I believe it downloaded correctly. However when I try to import pynput I am getting the error:

>>> import pynput
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "build/bdist.linux-x86_64/egg/pynput/__init__.py", line 23, in <module>
  File "build/bdist.linux-x86_64/egg/pynput/keyboard/__init__.py", line 49, in <module>
  File "build/bdist.linux-x86_64/egg/pynput/keyboard/_xorg.py", line 30, in <module>
ImportError: No module named Xlib.display

Hopefully someone can help,
Thanks

Error entering Unicode symbols on linux

I have this code which attempts to type a backspace and then a unicode symbol when a certain condition is met.

def on_press(key):
    try:
          if key.char == ';':
              if random.randint(0,20) == 5:
                  keyboard = Controller()
                  keyboard.type(u'\b')
                  keyboard.type(u'\u037E')

However when it tries to type the backspace it gives this error:

Traceback (most recent call last):
File "input_helper.py", line 105, in
listener.join()
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/_util/init.py", line 185, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "/home/jordan/.local/lib/python3.5/site-packages/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/_util/init.py", line 140, in inner
return f(self, *args, **kwargs)
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/_util/xorg.py", line 427, in _handler
self._handle(self._display_stop, event)
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/keyboard/_xorg.py", line 511, in _handle
self.on_press(key)
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/_util/init.py", line 71, in inner
if f(*args) is False:
File "input_helper.py", line 75, in on_press
keyboard.type(u'\u0008')
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/keyboard/_base.py", line 448, in type
self.release(character)
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/keyboard/_base.py", line 404, in release
self._handle(resolved, False)
File "/home/jordan/.local/lib/python3.5/site-packages/pynput/keyboard/_xorg.py", line 196, in _handle
raise self.InvalidKeyException(key)
pynput.keyboard._base.InvalidKeyException: '\x08'

it gives a similar error for the other unicode character if I remove the backspace so it can get there. This code works on windows but not on linux.

Non-synthetic Key.alt and Key.cmd

When I press Key.alt + Key.tab I'm expecting my OS (Ubuntu) to switch windows, but nothing happens.

When I start xev and issue Key.alt I see:

KeyPress event, serial 37, synthetic YES, window 0x5400001,
root 0x498, subw 0x0, time 0, (0,0), root:(0,0),
state 0x8, keycode 64 (keysym 0xffe9, Alt_L), same_screen NO,
XLookupString gives 0 bytes:
XmbLookupString gives 0 bytes:
XFilterEvent returns: False

while if I issue a real Alt on my qwerty keyboard I see:

KeyPress event, serial 37, synthetic NO, window 0x5400001,
root 0x498, subw 0x0, time 26110842, (20,-9), root:(85,43),
state 0x0, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
XLookupString gives 0 bytes:
XmbLookupString gives 0 bytes:
XFilterEvent returns: False

Most things are similar, but I noticed that "synthetic" is different. Is this the reason why I can't use pynput to control the OS? The behavior is the same with Key.cmd (Super/Win). FYI if I use PyUserInput it generates "synthetic NO" events in xev.

While listener is on, pressing mouse left button would cause mouse pointer hang up.

my code is rather simple

from pynput import mouse

def on_click(x, y, button, pressed):
    print('Key {0} was {1} at {2}'.format( button, 'Pressed' if pressed else 'Released', (x, y)))

with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

when used under windows, this would cause mouse pointer hanup, sometimes the mouse would start to come back after a while, but in a very unresponsive manner. all subsequent input event will not be captured.

please look into it if you have time.

MacOSX: Code not registering alphanumeric keys [Resolved: accessibility config needed]

I Tried running the code below on a macbookpro 8,1 , el capitan 10.11.6.
It only detected special keys, did not detect normal alphanumeric ones.... very odd.

screen shot 2017-05-20 at 12 19 50 pm

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        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()

Any idea?

Capturing Key Combinations

This might be more of a question than an issue, but due to being unable to find any information on it I feel there may be a chance this falls under "issue".

What I'm looking to do is capture the keys CTRL + C individually. The problem is that the "on_press" function in the example code returns a character like this: � (github can't show it, it's a square character)

The "on_release" likewise returns this: '\x03' Which I believe is ascii for ctrl^c

Is there any way I can capture the keypresses individually, without the fancy / strange characters? So the output would look like this:

key down: key.ctrl_l
key down: c
key up: key.ctrl_l
key up: c

I have done research and I understand there is "Controller.modifiers" which if is the solution, I'm completely clueless as how to implement it.

Thank you for your time, I hope this question isn't merely due to me missing something in the documentation.

Modifiers not being added to keyboard.Controller.modifiers making shfit_pressed, ctrl_pressed, etc. return false perpetually

I've opened this SO question , but everything else is so straightforward about pynput I'm starting to think this may be a bug. I have code that looks like this:

from pynput.keyboard import Controller, Listener

boo = True
keyboard = Controller()

fib_lst = [0, 1]


def on_release(key):
    with keyboard.modifiers as mods:
        print(mods)
        print(key)
        print(keyboard.shift_pressed)


Listener(on_release=on_release).start()

while boo:
    nxt = fib_lst[-1] + fib_lst[-2]
    input(nxt)
    fib_lst.append(nxt)

When I release a key it prints an empty set, the name of the key that I released, and False. This is the case regardless of whether or not I am holding down a modifier key. Is there something else I should be doing or does pynput have a bug?

fyi: I'm running pynput version 1.3.5 on python 3.6.1, Windows 7 Enterprise

Horizontal mouse scroll does not work

A horizontal mouse scroll on Windows does not work.
In 'mouse./_win32.py', the '_scroll' function uses the 'dy' variable on both SendInput calls. The second call should state 'mouseData=dx' (line 88).

Alt gr not working with icelandic keyboard layout

When using pynput with icelandic keyboard layout Alt_gr gets registered as an unknown key with keycode 65027 but normally the keycode should be 65406. This makes the @ symbol and a few other characters not work since they rely on the Alt_gr.

I've also noticed a similar behavior with Ctrl+Shift+Tab. Tab works, Ctrl+Tab works, Shift+Tab works but when I press Ctrl+Shift+Tab it gets registered as a completely different character (keycode 65056) which isn't even known by pynput. This was very easy to work around though since I could just map that keycode to the Ctrl+Shift+Tab press but unfortunately I can not use the same tactic when Alt_gr is not recognized

ValueError() with pynput 1.3.2 on FreeBSD 11

When I try to run pynput 1.3.2 (from pip) on FreeBSD 11.0 amd64, I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/neel/.local/lib/python2.7/site-packages/pynput/mouse/_base.py", line 78, in scroll
    self._scroll(dx, dy)
  File "/home/neel/.local/lib/python2.7/site-packages/pynput/mouse/_xorg.py", line 75, in _scroll
    self._check_bounds(dx, dy)
  File "/home/neel/.local/lib/python2.7/site-packages/pynput/mouse/_xorg.py", line 103, in _check_bounds
    raise ValueError()
ValueError

The commands I am trying to run include:

from pynput.mouse import Controller
Controller().scroll(0, 1)

Please advise

Supporting higher mouse button numbers

Mouse buttons with number higher than 9 are indistinguishable from each other on XOrg implementaion of mouse Listener. That's of course caused by enum Button which doesn't support buttons higher than 9 and thus listener reports Button.unknown.

I cannot see a reason for such limitation. Of course there is a workaround but I believe this should be changed anyway.

Workaround to detect button with number higher than 9 in listener:

from pynput import mouse

def number_aware_button(number):
    try:
        button = mouse.Button(number)
    except ValueError:
        button = mouse.Button.unknown
    button.button_number = number
    return button

def on_click(x, y, button, pressed):
    print('Button {0} {1} {2}'.format(
        button,
        button.button_number,
        'pressed' if pressed else 'released')
        )

with mouse.Listener(on_click=on_click) as listener:
    listener._button = number_aware_button
    listener.join()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.