15

How do I use PyAutoGUI to detect a keypress event? In my research, I could not make an example in this model:

import pyautogui

num = 0
if pyautogui.press('b'): # I know the right thing is not to use the press, but, what do I put in place?
    num = 1
Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
Mi Tavares
  • 161
  • 1
  • 1
  • 5

2 Answers2

13

Detecting keystrokes isn't possible in PyAutoGUI. You might want to try the Pynput module instead: https://pypi.org/project/pynput/

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
9

The python keyboard library provides the exact function you need:

import keyboard

if keyboard.is_pressed('b'):
    num = 1
Community
  • 1
  • 1
itsCobra98
  • 91
  • 1
  • 1
  • 2
    `keyboard` lib uses MIT license compared to GPL of `pynput`. But beware that in `keyboard` lib (a) "the Linux parts reads raw device files (/dev/input/input*) but this requires root" and (b) OS X support is experimental. – mihca Jul 31 '21 at 14:50