How to detect mouse click and keypress? - python

I want to find mouse click and key press is occur or not between start time and end time (starttime:9:30 and endtime:10:30) using Python script.
Python code is here:
from pynput.mouse import Listener
from pynput.keyboard import Key, Listener
def on_click(x, y, button, pressed):
if pressed:
print("Mouse clicked.")
def on_press(key):
print("key is pressed")
with Listener(on_click=on_click,on_press=on_press) as listener:
listener.join()
with this I am able to get the mouse click and key press, but I don't have idea for time-interval.

First of all your code didn't work for me.
I had to make some changes in order to test it.
The problem in my case were the events mouse and keyboard at the same time.
Here I post my changed code:
from pynput.keyboard import Key, Listener
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
if pressed:
print("Mouse clicked.")
def on_press(key):
print("key is pressed")
from pynput import keyboard
key_listener = keyboard.Listener(on_press=on_press)
key_listener.start()
with Listener(on_click=on_click) as listener:
listener.join()
(Source: Using Mouse and Keyboard Listeners Together in Python)
If you want to count seconds, minutes and so on, you can use time like #Ujjwal Dash said.
The Mouse events will be noticed if its between 1 and 10 seconds since the script was started.
import time
from pynput.keyboard import Key, Listener
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
delta_time = (int(time.time()-start_time))
if delta_time >=1 and delta_time <=10:
if pressed:
print("Mouse clicked.")
def on_press(key):
delta_time = (int(time.time()-start_time))
print(delta_time)
print("key is pressed")
start_time = time.time()
from pynput import keyboard
key_listener = keyboard.Listener(on_press=on_press)
key_listener.start()
with Listener(on_click=on_click) as listener:
listener.join()
delta_time ... time in seconds since script start
If you want it to listen to a specific time of the day, you can work with the unix time and convert it with the time module.
In this code the mouse will be noticed if it's between 7:00 and 10:00 localtime hours.
import time
from pynput.keyboard import Key, Listener
from pynput.mouse import Listener
def check_time():
t = time.localtime(time.time())
if t.tm_hour<= 10 and t.tm_hour>=7:
return True
else:
return False
def on_click(x, y, button, pressed):
if check_time():
if pressed:
print("Mouse clicked.")
else:
pass
def on_press(key):
print("key is pressed")
from pynput import keyboard
key_listener = keyboard.Listener(on_press=on_press)
key_listener.start()
with Listener(on_click=on_click) as listener:
listener.join()

I don't know much about it, but I think you could do use the function time from the module time. You can bind start = time.time() to your start button and end = time.time() to your end button. Then, for each interval use i = end - start.

Related

Auto-clicker program doesn't start when key is pressed

so I was trying to make an auto clicker, the other day and for some reason, when I try to activate it with the toggle_key ("t") the program doesn't start. I was following this tutorial https://www.youtube.com/watch?v=4hdK9Gey76E and it seems to work in the video. Can anyone explain why the program doesn't start when I turn it on?
import time
import threading
from pynput.mouse import Controller, Button
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="t")
clicking = False
mouse = Controller()
def clicker():
while True:
if clicking:
mouse.click(Button.left, 1)
time.sleep(0.001)
def toggle_event(key):
if key == TOGGLE_KEY:
global clicking
clicking = not clicking
click_thread = threading.Thread(target=clicker())
click_thread.start()
with Listener(on_press=toggle_event) as Listener:
Listener.join()

How do I check that the left click button is actively being held down?

I want to move my mouse down 10 pixels every time that my left click is held in.
import keyboard
import mouse
keyboard.wait('-')
while mouse.click('left') == True:
mouse.move(0, 100, absolute=False, duration=0.2)
I would recommend using libraries such as pyautogui and pynput like so:
from pynput.mouse import Listener
import pyautogui
x,y = pyautogui.position()
def on_click(x, y, button, pressed):
if pressed:
pyautogui.moveTo(x+10,y)
with Listener(on_click=on_click) as listener:
listener.join()

Custom trigger to execute failsafe in pyautogui

The default trigger of failsafe pyautogui is drag mouse to up-left corner. if i do that then the program will stop. How to change trigger, instead drag mouse i want set the trigger with keyboard input. for example if i press P key then the program will stop (the failsafe executed)
There isnt a way using pyautogui but it has been done using pynput. here is an example (pay attention to def keypress specifiaclly)
from random import random
from threading import Thread
from time import sleep
from pynput.mouse import Controller, Button
from pynput.keyboard import KeyCode, Listener
import pyautogui
delay = float(pyautogui.confirm(text='Choose Clicking Speed Per Second', title='Spook AutoClicker', buttons=['0.5','0.001']))
mouse = Controller()
class AutoClicker(Thread):
clicking = False
def run(self):
while True:
if AutoClicker.clicking:
mouse.click(Button.left)
sleep(delay)
def keypress(key):
if key == KeyCode(char="p"):
AutoClicker.clicking = not AutoClicker.clicking
AutoClicker().start()
with Listener(on_press=keypress) as listener:
listener.join()

Use while loop inside pynput's mouse listener

The while loop returns true even when I have let go of the left mouse button which would make pressed = false. I don't know how to break out of the loop to update the pressed value.
from pynput import keyboard
from pynput import mouse
from pynput.mouse import Button, Controller
control = Controller()
def on_click(x, y, button, pressed):
if button == mouse.Button.left:
while pressed == True:
print(pressed)
with mouse.Listener(
on_click=on_click) as listener:
listener.join()
Is there any way to update the loop so it knows when pressed = false.
If you really have to run some loop then you have to do it in separted thread because if you run it in on_click then you block listener and it can't run another on_click
on_click should start loop in thread and use global variable to control when it should stop.
from pynput import mouse
from pynput.mouse import Button, Controller
import threading
control = Controller()
running = False
def process():
print('start')
count = 0
while running:
print(count)
count += 1
print('stop')
def on_click(x, y, button, pressed):
global running # to assing value to global variable (instead of local variable)
if button == mouse.Button.left:
if pressed:
if not running: # to run only one `process`
running = True
threading.Thread(target=process).start()
else:
running = False
with mouse.Listener(on_click=on_click) as listener:
listener.join()

Using Mouse and Keyboard Listeners Together in Python

I have been using pynput library for monitoring the clicks of the mouse.The only problem I am facing is that the terminal does not terminate on pressing Ctrl+C. I need to use keyboard listener with mouse listener. Here's my code:
import os
import time
import re
from pynput import mouse
from pynput.keyboard import Key, Listener
f=open('maniac1.txt','a')
inc=1
f.write('<mouse_new>\n')
def on_click(x, y, button, pressed):
f=open('maniac1.txt','a')
if button == mouse.Button.left:
print 'Left'
f.write('left\n')
if button == mouse.Button.right:
print 'right'
f.write('right\n')
if button == mouse.Button.middle:
print 'middle'
f.write('middle\n')
with mouse.Listener(on_click=on_click,on_scroll=on_scroll) as listener:
try:
listener.join()
except MyException as e:
print('Done'.format(e.args[0]))
How can i terminate this code after pressing Esc or Ctrl+C?I am using OSX.
Create an instance keyboard.Listener without "with" keyword so that you can start and stop the listener based on your mouse listener. Check the below code which will stop listening to key-press of f8 after right click by mouse.
import os
import time
import re
from pynput import mouse
from pynput.keyboard import Key, Listener
#f=open('maniac1.txt','a')
inc=1
#f.write('<mouse_new>\n')
from pynput import keyboard
def on_functionf8(key):
if (key==keyboard.Key.f8):
print('f8 is pressed')
key_listener = keyboard.Listener(on_release=on_functionf8)
key_listener.start()
def on_click(x, y, button, pressed):
f=open('maniac1.txt','a')
if button == mouse.Button.left:
print ('Left')
#f.write('left\n')
if button == mouse.Button.right:
key_listener.stop()
print ('right')
#f.write('right\n')
if button == mouse.Button.middle:
print ('middle')
#f.write('middle\n')
with mouse.Listener(on_click=on_click) as listener:
try:
listener.join()
except MyException as e:
print('Done'.format(e.args[0]))
run the program and press f8 and you will see 'f8 is pressed' on the terminal. But right click and press f8. You wont see anything printed as we stopped the keyboard listener on right click of mouse.
for mac:
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
key_listener = keyboard.Listener(on_release=on_press)
only few keys like cmd, alt are listened on mac by default.
This code using mouse and keyboard listeners together.
from pynput.keyboard import Listener as KeyboardListener
from pynput.mouse import Listener as MouseListener
from pynput.keyboard import Key
import logging
logging.basicConfig(filename=("log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def end_rec(key):
logging.info(str(key))
def on_press(key):
logging.info(str(key))
def on_move(x, y):
logging.info("Mouse moved to ({0}, {1})".format(x, y))
def on_click(x, y, button, pressed):
if pressed:
logging.info('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
def on_scroll(x, y, dx, dy):
logging.info('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
with MouseListener(on_click=on_click, on_scroll=on_scroll) as listener:
with KeyboardListener(on_press=on_press) as listener:
listener.join()
I've just finished the same thing a few hours ago, here is what I wrote.
First add another keyboard listener:
# 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()
Then add the on_release function:
def on_release(key):
if key == keyboard.Key.esc:
# Stop listeners
m_listener.stop()
return False
Then if you press Esc this code will be terminate.
For OSX you need to run python with sudo or it won't work fine.

Categories

Resources