How do I print out from the function? - python

I try to write some click-event program using pynput library. I can't find out how to print counter out from the function to use it further.
root.counter = 0
def on_click(x, y, button, pressed):
if pressed:
root.counter += 1
logging.info(str(root.counter) + '. Mouse clicked at ({0}, {1}) with {2}'.
format(x, y, button))
print('Button clicked: ' + str(root.counter))
if not pressed:
# Stop listener
return False
listener = mouse.Listener(on_click=on_click)
listener.start()

Related

Why when I make this function return its value, the function repeats itself infinitely?

This is my code, and in the line, I put a commentary about the return that makes this problem.
from pynput import mouse
def on_move(m_x, m_y):
print('Pointer moved to {0}'.format((m_x, m_y)))
def on_click(m_x, m_y, button, pressed):
#print('{0} at {1}'.format('Pressed' if pressed else 'Released',(m_x, m_y)))
if(pressed):
print("Pressed")
else:
print("( x = "+ str(m_x) + ", y = " + str(m_y) + " )")
return(m_x, m_y) #this is the return
if not pressed:
# Stop listener
return False
def on_scroll(m_x, m_y, dm_x, dm_y):
print('Scrolled {0} at {1}'.format(
'down' if dy < 0 else 'up',
(m_x, m_y)))
# Collect events until released
with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
A_coord_x, A_coord_y = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
#listener.start()
print (A_coord_x)
print (A_coord_y)
The only thing I want is that after giving a click the coordinates are saved in the variables A_coord_x and A_coord_y
here is the answer for you. this will release the listener and get you the coordinates in A_coord_x and A_coord_y
from pynput.mouse import Listener
A_coord_x, A_coord_y = 0, 0
def on_click(x, y, button, pressed):
global A_coord_x, A_coord_y
if pressed:
A_coord_x, A_coord_y = x, y
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
return x,y
if not pressed:
# Stop listener
return False
with Listener(on_click=on_click) as listener:
coords = listener.join()
print ('X coordinates :',A_coord_x)
print ('Y coordinates :',A_coord_y)
output:
Pressed at (1211, 400)
X coordinates : 1211
Y coordinates : 400
on_click() is an event handler, you can't return values from it, the return False statement just stops the listener. Just call a set_coordinates(x,y) function from within the handler and you should get your intended result.
Maybe also take a look at the documentation, there is an example on how to work with the mouse.listener

Is there a way to bypass the need to reference self in an argument (Python)

The purpose of my code is to create and print a list of all the keyboard and mouse interactions that occur. The code was working, but then I decided to convert it into a class. From there, I was not able to reference the functions because it considered self to be the first argument.
Here is the code with the class that does not work.
import pyautogui
from pynput.mouse import Listener
MouseListener = Listener
from pynput.keyboard import Listener
KeyboardListener = Listener
from pynput import keyboard
######################
#
# m = move
# p = mouse press
# r = mouse release
# d = scroll down
# u = scroll up
# 1 = key down
# 2 = key up
#
######################
temp = []
class Recorder():
#record mouse movement
def on_move(self, x, y):
temp.append('m{0}'.format(
(x, y)))
#record mouse click
def on_click(self, x, y, button, pressed):
temp.append('{0}{1}'.format(
'p' if pressed else 'r',
(x, y)))
#record mouse scroll
def on_scroll(self, x, y, dx, dy):
temp.append('{0}{1}'.format(
'd' if dy < 0 else 'u',
(x, y)))
#record keyboard press
def on_press(self, key):
try:
temp.append('1({0})'.format(
key.char))
except AttributeError:
temp.append('1({0})'.format(
key))
#record keyboard release and end if esc
def on_release(self, key):
temp.append('2({0})'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
print(temp)
keyboard_listener.stop()
mouse_listener.stop()
return False
mouse_listener = MouseListener(
on_move=Recorder.on_move,
on_click=Recorder.on_click,
on_scroll=Recorder.on_scroll)
keyboard_listener = KeyboardListener(
on_press=Recorder.on_press,
on_release=Recorder.on_release)
keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()
And below is the code that performs properly.
import pyautogui
from pynput.mouse import Listener
MouseListener = Listener
from pynput.keyboard import Listener
KeyboardListener = Listener
from pynput import keyboard
##########
#
# m = move
# p = mouse press
# r = mouse release
# d = scroll down
# u = scroll up
# 1 = key down
# 2 = key up
#
##########
temp = []
#mouse recorder
def on_move(x, y):
temp.append('m{0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
temp.append('{0}{1}'.format(
'p' if pressed else 'r',
(x, y)))
def on_scroll(x, y, dx, dy):
temp.append('{0}{1}'.format(
'd' if dy < 0 else 'u',
(x, y)))
#keyboard recorder
def on_press(key):
try:
temp.append('1({0})'.format(
key.char))
except AttributeError:
temp.append('1({0})'.format(
key))
def on_release(key):
temp.append('2({0})'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
print(temp)
keyboard_listener.stop()
mouse_listener.stop()
return False
#activation
mouse_listener = MouseListener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll)
keyboard_listener = KeyboardListener(
on_press=on_press,
on_release=on_release)
keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()
You can use the decorator #staticmethod for this. Add #staticmethod above the functions in question. For example:
class Recorder:
#record mouse movement
#staticmethod
def on_move(x, y,temp):
temp.append('m{0}'.format((x, y)))
You can now use the function without instantiating an object.
Call the function with:
Recorder.on_move(x,y,temp)
Documentation

Make pynput mouse listener less resource-hungry

I'm trying to use This script from pynput to monitor my mouse, but its too resource-intensive.
Tried to import time and add time.sleep(1) after on_move(x, y) function but when you run it your mouse drives crazy.
Here's the overall code:
import time
def on_move(x, y):
print('Pointer moved to {0}'.format((x, y)))
time.sleep(1) # <<< Tried to add it over here cuz it takes most of the process.
def on_click(x, y, button, pressed):
print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y)))
if not pressed:
return False
def on_scroll(x, y, dx, dy):
print('Scrolled {0}'.format((x, y)))
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
You could use a thread to run your code when do some task which will block your code.(In your code, sleep(1) will block the code),Whatever, this works fine on my PC:
from pynput.mouse import Listener
import time
import threading
def task(): # this is what you want to do.
time.sleep(1) # <<< Tried to add it over here cuz it takes most of the process.
print("After sleep 1 second")
def on_move(x, y):
print('Pointer moved to {0}'.format((x, y)))
threading.Thread(target=task).start() # run some tasks here.
def on_click(x, y, button, pressed):
print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y)))
if not pressed:
return False
def on_scroll(x, y, dx, dy):
print('Scrolled {0}'.format((x, y)))
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()

How to take control of user mouse movements when a user shares his screen through skype or MS teams?

I have used python code with pynput library and it worked fine to track my mouse movement in my system.
Our need is now to track the same mouse movements when user shares his screen through Skype/MS Teams ?
Please help.
We tried the below code.
from pynput import mouse
def on_move(x, y):
pass
# 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} at {1}'.format(
'down' if dy < 0 else 'up',
(x, y)))
# Collect events until released
with mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(
on_move=on_move,
#on_click=on_click,
on_scroll=on_scroll)
listener.start()

Record (get) mouse click position while key is pressed and stop recording when same key is released in python

I am creating a script where if user press f7 it will start recording mouse clicks and when he releases the button it should stop and this happens unless user closes the program.
The script is printing "None" inspite of pressing f7 and instead of showing click position and "f7", it is showing None.
In on_press function when we print the value, it is showing "f7" but when clicking the mouse button in on_click function, it is showing "None"
Here is the code
from pynput import mouse, keyboard
from pynput.keyboard import Key, Listener
import pickle
x_pos = []
y_pos = []
both_pos = []
pressed_key = None
def on_press(key):
if (key==keyboard.Key.f7):
pressed_key = "f7"
else:
pressed_key = None
def on_release(key):
pass
def on_click(x, y, button, pressed):
if pressed:
#print ("{0} {1}".format(x,y))
print(pressed_key)
if pressed_key == "f7":
x_pos.append("{0}".format(x,y))
y_pos.append("{1}".format(x,y))
#print("test" + x_pos + y_pos)
print (x_pos + y_pos)
#both_pos = x_pos, y_pos
else:
pass
print (x_pos + y_pos)
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
try:
#listener.start()
listener.join()
except MyException as e:
print('Done'.format(e.args[0]))
Found the issue. Because in on_press i was not using global pressed_key so it was creating local variable.
Here is the working code.
from pynput import mouse, keyboard
from pynput.keyboard import Key, Listener
import pickle
x_pos = []
y_pos = []
both_pos = []
pressed_key = None
def on_press(key):
global pressed_key
if (key==keyboard.Key.f7):
pressed_key = "f7"
print(pressed_key)
else:
pressed_key = None
def on_release(key):
global pressed_key
pressed_key = None
def on_click(x, y, button, pressed):
if pressed:
#print ("{0} {1}".format(x,y))
print(pressed_key)
if pressed_key == "f7":
x_pos.append("{0}".format(x,y))
y_pos.append("{1}".format(x,y))
#print("test" + x_pos + y_pos)
print (x_pos + y_pos)
#both_pos = x_pos, y_pos
else:
pass
print (x_pos + y_pos)
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
try:
#listener.start()
listener.join()
except MyException as e:
print('Done'.format(e.args[0]))

Categories