How to Send Virtual Keypresses in Python with the pyautogui Module



Python


In this article, we show how to send virtual keypresses in Python with the pyautogui Module.

A keypress doesn't have to happen manually, as in I typing some keys or you doing so. We can perform a keypress in our code to type anything in.

pyautogui is a module that can do many different dynamic things, including sending virtual keypresses and mouse clicks to Windows.

With it, we can type something on the screen.

So to send a virtual keypress with the pyautogui module, we use the, pyautogui.typewrite() function. Inside of this function, we specify the character or the string we want to type.

In this example, we'll print out to the screen, 'Python is a great language'

So what you should do is open up a text editor, such as notepad or a Word processor such as Microsoft Word. Make the screen large and then open up your Python IDE.

Type in the following lines of code shown below.



So let's now go over the code.

The first thing we must do is import the pyautogui module.

We then use pyautogui.click(100,100) just so that we can click off of the Python IDE and onto the text editor that you opened. If you don't click away from the Python IDE, it will type, 'Python is a great language' in the Python IDE.

We want it done somewhere else so that we can see Python writing to another piece of software such as a text editor.

And after you run this code, you should see, 'Python is a great language' written inside of the text editor.

Knowing how to send virtual keypresses in Python is useful for automating any typed messages that should appear somewhere on a screen.

And this is how we can send virtual keypresses in Python using the pyautogui module.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...