views:

267

answers:

2

Python and 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()

For some reason this program fails after running it exactly two times, I have no idea what the cause for this is. When you comment out the SendKeys part the program runs fine, so it has to be a problem with send keys.

[edit] Also, to clarify, running SendKeys.SendKeys(...) in a for i in range(0,100) works, so I assume it's something to do with the thread. I've never programmed threads before. Also this is just a mockup example to replicate the problem.

I'm running on windows 7, python2.6

[edit]Also, the program doesn't 'fail' it simply freezes (the function isn't run at all, it just sits there)

A: 

I am not so sure with the program but if you put exit(); in the middle of the program, It will quit program completely.

So Could you try without exit();?

S.Mark
I thought that it will only close the thread?But I tried it and it didn't do anything differently.
ok, btw, above codes is full program? I don't see threading part.
S.Mark
Yip, it's the full programAuto().start();#Starts the thread
ok, let me try to regenerate your problem.
S.Mark
+1  A: 

It seems that SendKeys is thread safe. The following code works on 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()

Maybe the problem comes from some interferences with PyHook or the Windows PumpMessage mechanism. Have you tried to put the SendKeys part in a different process rather than in a different thread?

I hope it helps

luc
I just tried doing it the module 'multiprocessing' and creating a new process, I still get exactly the same problem.No idea why it works the first time around but not the second time. Maybe I should close something? I'm just guessing here, it maybe something like opening a file in python and not closing it after the program has run for other processes to edit that file or something similar.