我正在尝试制作一个在按下鼠标按钮时从 0 开始计数的 python 脚本。我的想法是使用 pyHook 在按下鼠标左键时进入一个函数,并在释放鼠标左键时退出该函数。我对python很陌生,很抱歉解释不好。一些伪代码:
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()
这段代码是我的一般想法,但我认为它不会起作用,因为 SubscribeMouseLeftUp 发生在离散时间。我正在寻找的可能是在某种线程或多处理模块中运行计数器函数和终止函数,并在一个函数中使用条件来终止另一个正在运行的函数。但我不知道如何使这项工作。
好的,所以我在 willpower 的评论之后尝试了这个脚本:
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()
willpower2727 接受的答案是迄今为止我见过的最好的解决方案。在他使用线程发布他的解决方案之前,我编写了以下代码:
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()
我对这段代码的预期行为是 counter 和 mousesignal 函数应该作为单独的进程运行。在鼠标信号过程中,我根据鼠标输入将 0 或 1 放入队列。计数器函数连续运行并读取队列并使用 if 语句进入和退出该函数中的循环。这段代码根本不起作用,但我不明白为什么。