Simulating Keyboard Strokes Using Python

As part of the Data Structures course in university, we were assigned a task to create a record system using doubly linked list. Everything went well: I planned the project, read the book for references, and finally started coding –until– I had to manually test the program myself.

I programmed in XCode, which didn’t provide (or at least that I was aware of) automated unit tests for programs in C. So I had to manually enter all the input myself — each time I ran the program. So much so, I spent more time typing the inputs than programming itself (note: I said programming, not just coding).

It took me awhile, but I remembered some guy wrote a book called “Automating th boring stuff with Python”. I finally dawned on me that what I did fell into this ‘boring’ category. So I thought “Hmmm, can I automate this using python?’. I opened up Chrome and started searching. And Voila! There it is.

So first, as usual, import the required modules.

from pynput.keyboard import Key, Controller

If you don’t have pynput module, just install it using pip

pip3 install pynput

I had to use pip3 since a warning came up “Python 2 is going to be deprecated bla bla…”.

Then assign the method Controller() to a variable. So we can call this method by just typing “keyboard” later.

keyboard = Controller()
Image source: me

Done! Say I want my computer to type in “Krishna”, I just need this command:

keyboard.type('Krishna') 
#don't forget to put the string between quotes here.

Or I want it to press the enter button

keyboard.enter(Key.enter)

Additional notes:

In XCode, there’s a delay after I pressed enter and the next command. Humans, including me, won’t be bothered by this. But if I simulate all the keystrokes in consecutive order, XCode will throw an error and go haywire, BAD THREAD ACCESS thing.

So I had to introduce a delay after the enter was pressed and the next keystroke. I managed it using the time module.

import time

keyboard.type('Krishna')
keyboard.enter(Key.enter)

#I need the delay here, so
time.sleep(1)

#Another command bla bla....
#.....

If you want, you can change the sleep value to a smaller float number, say 0.5 or 0.3 –but not 0.1, it’s still faster than the XCode delay, so there’s no point in that.

Leave a comment

Website Powered by WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started