线程中SendKeys在运行两次后失败
Python 和 SendKeys
import SendKeys, threading, pyHook, pythoncom
class Auto(threading.Thread):
def run(self):
SendKeys.SendKeys("{ENTER}",pause=0.1);
print('Sent');
exit();
def OnKeyboardEvent(event):
if event.Ascii == 22:
Auto().start();
return True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
这个程序在运行了两次后就出问题了,我也不知道为什么。把 SendKeys 的部分注释掉后,程序就能正常运行,所以问题肯定出在 SendKeys 上。
[编辑] 另外,想说明一下,在 for i in range(0,100) 里运行 SendKeys.SendKeys(...) 是没问题的,所以我猜可能和线程有关。我之前从来没有编写过线程的代码。而且这只是一个示例,用来复现这个问题。
我是在 Windows 7 上运行,使用的是 Python 2.6。
[编辑] 还有,程序并不是“失败”,而是直接卡住了(这个功能根本没有运行,就在那里不动了)。
2 个回答
0
我对这个程序不是很确定,不过如果你在程序中间加上 exit();
,那么程序就会完全退出。
所以你能试试看不加 exit();
吗?
1
看起来SendKeys是线程安全的。下面的代码在Vista系统上可以正常运行 - Python 2.6
class Auto(threading.Thread):
def run(self):
SendKeys.SendKeys("#",pause=0.1);
print('Sent');
exit();
for i in xrange(30):
Auto().start()
可能问题出在PyHook或者Windows的PumpMessage机制上。你有没有试过把SendKeys的部分放在一个不同的进程里,而不是放在不同的线程中呢?
希望这能帮到你