I'm trying to make a python script that starts counting from 0 when the mouse button is pressed. My idea is to use pyHook to go into a function when left mouse button is pressed and exit the function when left mouse is released. I'm pretty new to python so sorry for bad explanations. Some pseudocode:
import pyHook
import pythoncom
def termin():
return None
def counter(tell):
a=0
while True:
print a
a+=1
hm = pyHook.HookManager()
hm.SubscribeMouseLeftUp(termin)
hm = pyHook.HookManager()
hm.SubscribeMouseLeftDown(counter)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
This code is my general idea, however I don't think it will work because SubscribeMouseLeftUp happens at a discrete time. What i'm looking for is maybe running the counter function and termin function in some kind of threading or multiprocessing module and use conditions in one function to terminate the other running function. But I'm not sure how to make this work.
Okay, so I tried this script after willpower's comment:
import pyHook,time,pythoncom
def counter(go):
for a in range(5):
time.sleep(1)
print a
return True
hm=pyHook.HookManager()
hm.SubscribeMouseLeftDown(counter)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
The accepted answer from willpower2727 is the best solution I've seen so far. Before he posted his solution using threading I made the following code:
from multiprocessing import Process,Queue
import pyHook
import time
import pythoncom
import ctypes
def counter(tellerstate,q):
while True:
a=0
tellerstate=q.get()
if tellerstate==1:
while True:
a+=1
print a
tellerstate=q.get()
if tellerstate==0:
break
time.sleep(0.1)
def mousesignal(q):
def OnDown(go):
tellstate=1
q.put(tellstate)
return None
def OnUp(go):
tellstate=0
q.put(tellstate)
return None
def terminate(go):
if chr(go.Ascii)=='q' or chr(go.Ascii)=='Q':
ctypes.windll.user32.PostQuitMessage(0)
hm.UnhookKeyboard()
hm.UnhookMouse()
q.close()
q.join_thread()
process_counter.join()
process_mousesignal.join()
return None
hm=pyHook.HookManager()
hm.KeyDown = terminate
hm.MouseLeftDown = OnDown
hm.MouseLeftUp = OnUp
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()
if __name__ == '__main__':
tellerstate=0
q=Queue()
process_counter = Process(target=counter,args=(tellerstate,q))
process_mousesignal = Process(target=mousesignal,args=(q,))
process_mousesignal.start()
process_counter.start()
My expected behaviour of this code is that the counter and mousesignal functions should run as separate processes. In the mousesignal process I'm putting either a 0 or 1 to a Queue based on mouse input. The counter function runs continuously and reads the Queue and uses if statements to enter and quit the loop in this function. This code doesn't work at all, but I can't understand why.