Skip to main content
 首页 » 编程设计

python之SendKeys 在线程中运行 2 次后失败

2025年05月04日11kevingrace

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 部分时,程序运行正常,因此它一定是发送 key 的问题。

[edit] 另外,为了澄清,在 for i in range(0,100) 中运行 SendKeys.SendKeys(...) 是可行的,所以我认为这与线程有关。我以前从未编写过线程。此外,这只是一个复制问题的模型示例。

我在windows 7上运行,python2.6

[edit]此外,程序不会“失败”,它只是卡住(函数根本不运行,它只是坐在那里)

请您参考如下方法:

看来 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 部分放在不同的进程而不是不同的线程中?

希望对你有帮助