i cant find a solution for the following problem:
I would like to record keystrokes and mousemovement at the same time. Right now i tried to combine the scripts from the pynput Package Documentation.
Monitoring the mouse: https://pynput.readthedocs.io/en/latest/mouse.html#monitoring-the-mouse
Monitoring the keyboard:
https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard
from pynput import mouse
from pynput import keyboard
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
def on_scroll(x, y, dx, dy):
print('Scrolled {0}'.format(
(x, y)))
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 mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Right now the keyboard listener only starts after the mouse listener gets closed. Is there any way to record mouse and keyboard at the same time? Are there better site-packages for this? Thanks a lot in advance!
All you need is this, my friend
# Collect events until released
with keyboard.Listener(on_release=on_release) as k_listener, mouse.Listener(on_click=on_click) as m_listener:
k_listener.join()
m_listener.join()
Related
Here is my prank code for my friend but I can not stop this program from keyboard when I make executable.
How can I stop this listener from keyboard shortcut. I know it is thread issue.
import sys
import pyautogui
import keyboard
from pynput.mouse import Listener
from threading import Thread
global x,y
def on_move(x, y):
print ("Mouse moved to ({0}, {1})".format(x, y))
def on_click(x, y, button, pressed):
try: #FOR AUTO FAIL-SAFE
if pressed:
print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
pyautogui.move(x+100,y+100)
except:
pass
def on_scroll(x, y, dx, dy):
print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
while True:
if keyboard.is_pressed("q"):
sys.exit(0)
break
So here is my fix. I works because I had the same problem:
Insert:
from pynput.keyboard import Key
then:
In on_move(), on_click(), and on_scroll() add:
if key == Key.f10:
sys.exit()
This will check that when you press f10 (or you can change), the program will exit
You also need to pass key as an argument!
The full updated code is:
import sys
import pyautogui
import keyboard
from pynput.keyboard import Key
from pynput.mouse import Listener
from threading import Thread
global x,y
def on_move(key, x, y):
print ("Mouse moved to ({0}, {1})".format(x, y))
if key == Key.f10:
sys.exit()
def on_click(key, x, y, button, pressed):
try: #FOR AUTO FAIL-SAFE
if pressed:
print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
pyautogui.move(x+100,y+100)
except:
pass
if key == Key.f10:
sys.exit()
def on_scroll(key, x, y, dx, dy):
print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
if key == Key.f10:
sys.exit()
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
while True:
if keyboard.is_pressed("q"):
sys.exit(0)
break
I solved this problem. When mouse position(x,y) on left-top and mid scrolled. Program finishes itself.
def on_scroll(x, y, dx, dy):
print('Scrolled {0} at {1}'.format(
'down' if dy < 0 else 'up',
(x, y,dx,dy)))
if x<100 and y<100:
return False
I am trying to make a windows analog of the Chat-wheel from Dota 2 or Battlefield with some fast commands like this.
How it should be:
While the G-key is pressed - the wheel with some sections appears at the centre of the screen, with the mouse centered on it and if I move the mouse to side_1 and then release the G-key -> func_1 executes.
If it was on side_2 -> func_2.
If I release the G-key at the centre -> wheel disappears and nothing happens.
So to monitor the X Y coordinates of the mouse I use following code:
from pynput import mouse
def on_move(x, y):
print(x, y)
# Collect events until released
with mouse.Listener(on_move=on_move) as listener:
listener.join()
It is spamming coordinates when I move the mouse.
But I am stuck in the part where i need:
to start the listener from another .py file and take these coordinates for the visual part of the program (like highlight the side of the wheel with command descriptions),
to close the listener from another .py file and take the last coordinates of the mouse when the G-key is released to compare with tge range of coordinates prescribed for functions.
You want something like this:
from pynput import mouse, keyboard
import time
def on_press(key):
print("pressed {}".format(key))
def on_release(key):
print("released {}".format(key))
def on_move(x,y):
print((x,y))
mouse_listener = mouse.Listener(
on_move=on_move)
mouse_listener.start()
key_listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
key_listener.start()
# prevent the script from exiting immediately
time.sleep(10)
import time
import keyboard
from pynput.mouse import Controller
def get_xy():
mouse = Controller()
mouse_coord = str(mouse.position)
mouse_coord = mouse_coord.replace("(", "")
mouse_coord = mouse_coord.replace(")", "")
mouse_coord = mouse_coord.replace(",", "")
mouse_coord = mouse_coord.split(" ")
mouse_x = int(mouse_coord[0])
mouse_y = int(mouse_coord[1])
print(mouse_x, mouse_y)
while True:
if keyboard.is_pressed('b'):
get_xy()
time.sleep(0.01)
Output example: 654 326
So I'm trying to make the program not run in an endless loop once pressed is true and check for when the mouse button is released and stop the while loop.
from pynput import mouse
from pynput.mouse import Button, Controller
import time
m = Controller()
def on_click(x, y, button, pressed):
print('Pressed' if pressed else 'Released')
while (pressed):
m.move(0, 1)
time.sleep(.001)
with mouse.Listener(
on_click=on_click) as listener:
listener.join()
Something like this. Don't try to sleep for 1ms, you'll waste too many resources.
from pynput import mouse
from pynput.mouse import Button, Controller
import time
m = Controller()
mousedown = False
def on_click(x, y, button, pressed):
global mousedown
print('Pressed' if pressed else 'Released')
mousedown = pressed
listener = mouse.Listener(on_click=on_click)
while True:
if mousedown:
m.move( 0, 1 )
time.sleep( 0.1 )
I'm trying to understand an example from the pynput documentation.
I understand the general gist, that the code prints a message when the mouse moves/is clicked/etc. I'm just confused about how it does so.
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
with mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()
I'm trying to detect what mouse button was clicked
so here is my code:
from pynput.mouse import Listener
def on_click(button, pressed):
if button.Left and pressed:
print("You pressed the left mouse button")
if button.Right and pressed:
print("You pressed the right mouse button")
so there was no errors but It's not working any Ideas?
From the Documentation Here
CODE
from pynput import mouse
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print(button) # Print button to see which button of mouse was pressed
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
# Collect events until released
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_click=on_click)
listener.start()
As you can see, the button parameter in the function on_click tells you which button was pressed.
EDIT:
Here is how you may handle action based on which button of the mouse was pressed
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
print('Left if Pressed')
# ====== < Handle Pressed or released Event ====== > #
if pressed:
print('Do somethin when Pressed with LEft')
else:
print('LEFT is Released')
elif btn == 'right':
print('Right BTN was pressed ')
# ====== < Handle Pressed or released Event ====== > #
if not pressed:
print('right Button is released')
else:
pass
I post a second answer because of a different nature of the issue found on code here
The issue is how you call the imports.
CORRET CODE
from pynput import mouse
mouse_ = mouse.Controller()
button = mouse.Button
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
if pressed:
mouse_.click(button_.left)
print('works')
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
Copy and Paste the code without changes.
WARNING
when I use button.left my pc becomes extremely lagy so i suggest you to don't use is unless you know what you are doing