Sending keystrokes to Windows exe programs

Chris Angelico rosuav at gmail.com
Sat Apr 2 15:42:10 EDT 2011


On Sun, Apr 3, 2011 at 2:48 AM, Alex van der Spek <zdoor at xs4all.nl> wrote:
> I can start a windows program on Vista with:
>
>>>> import subprocess
>>>> dva=subprocess.Popen(DVAname,stdin=subprocess.PIPE)
>
> Unfortunately sending keystrokes with communicate() does not appear to work:
>
>>>> dva.communicate('F2')
>
> this does not produce any result but it does make IDLE become really idle.

Amusing. :)

>>>> dva.terminate()
>
> however does work fine and kills the program as it should.
>
> Is there a way or do I have to go back to Visual Basic?

I've not used the subprocess module actually, and your post suggests
that what I've been doing may be suboptimal, but in the Yosemite
project I have this code:


                import win32api
                def dokey(key1,key2=None):
                        win32api.keybd_event(key1,0,0,0)
                        if key2!=None:
                                win32api.keybd_event(key2,0,0,0)
                                win32api.keybd_event(key2,0,2,0)
                        win32api.keybd_event(key1,0,2,0)
                shift=16; ctrl=17; left=37; right=39; space=32

To send Shift-Right Arrow, I call:
dokey(shift,right)

(This code multiplexes its options for cross-platform capabilities,
taking advantage of the fact that Python allows you to define
functions inside an if block.)

win32api.keybd_event is a fairly "raw" call that just passes its
parameters straight through to the underlying keybd_event Windows API.
It doesn't send keys to a specific window, it instead sends keys to
"whichever window currently has focus" (which is what I want for
Yosemite). Not sure if that's suited to your needs.

Chris Angelico



More information about the Python-list mailing list