Keyboard Automation in Python using PyAutoGUI

In this tutorial, we’ll learn about Keyboard Automation in Python using PyAutoGUI. PyAutoGUI is a module in Python that can automate Mouse movements as well as keystrokes. Keyboard automation in Python using PyAutoGUI has many applications in robotics. To read more about this amazing module, go visit its documentation.

So, let’s start!

Writing simple characters

We will use the write() function so as to simulate typing on our keyboard. The interval parameter will cause a delay between each character typed.

import pyautogui as gui
gui.write("Hi! you're reading CodeSpeedy!",interval=1)

Notepad text Typing

Pressing keys

The write() function can only press single character type keys. To press ‘shift’ or ‘enter’, we need to use the press() function.

gui.press('enter')
gui.press(['enter','\t','\t','volumedown'])

We can also press multiple keys one after another by passing them as a list.

Output:

Notepad

There are also functions like keyDown() and keyUp(). We use them in cases where we need to hold down ‘shift’ and the ‘left’ key (say) to select a part of the sentence.

gui.keyDown('shift')
gui.press('left',presses=15)
gui.keyUp('shift')

Output:

notepad

Pressing Hotkeys

All of us use keyboard shortcuts pretty often. The keyboard shortcuts like ‘Ctrl’+’Alt’+’Delete’ to open the task manager and ‘Ctrl’+’c’ to copy, etc are also called Hotkeys. The hotkey() function presses and holds in order and releases in its reverse order.

gui.hotkey('ctrl','shift','delete')

Sample program

Now we’ll see a simple program to copy a text from a text editor and paste it 5 times using keyboard automation.

gui.click(100,0)
gui.write("HI! YOU'RE READING CODESPEEDY!")
gui.press('enter',presses=3)
gui.keyDown('shift')
gui.press(['up','up','up'])
gui.keyUp('shift')
gui.hotkey('ctrl','c')
gui.press('down',presses=3)
for i in range(5):
    gui.hotkey('ctrl','v')

Let’s breakdown the above code.
First, lines 2-3 writes the text to be copied.
Next, lines 4-6 selects the text to be copied.
Further, line 7 copies the selected text.
Lastly, lines 8-10 pastes the text 5 times.

Output:

Notepad

Also, see:

Leave a Reply

Your email address will not be published. Required fields are marked *