Overview
This article explains how to automate keyboard operations using the PyAutoGUI library in Python. It covers not only simple text input using the write method but also complex operations like holding down modifier keys (keyDown/keyUp) and using shortcut keys (hotkey).
Specifications
- Input: Text strings, specific key names (Enter, Shift, Ctrl, etc.), and time intervals between inputs.
- Output: Simulated physical keyboard signals sent to the OS.
- Requirements: The
pyautoguilibrary must be installed. - Note: This guide focuses on alphanumeric input. For non-English characters, use a clipboard-based method.
Basic Usage
This is a basic implementation to type a string and press the Enter key. We use the write function, which is the standard method for typing text.
import pyautogui
# Safety feature: Move mouse to a corner to stop the script
pyautogui.FAILSAFE = True
# Type "Hello" with a 0.1-second interval between characters, then press Enter
pyautogui.write(['H', 'e', 'l', 'l', 'o', 'enter'], interval=0.1)
Full Code Example
The following code demonstrates a practical sequence: typing text, selecting a range by holding the Shift key, and copying text using a shortcut.
import pyautogui
import time
def automate_text_editing():
"""
Demonstration of automated text editing.
Please open a text editor and make it active before running this script.
"""
pyautogui.FAILSAFE = True
print("Starting in 3 seconds. Please activate your text editor...")
time.sleep(3)
try:
# 1. Type text string
print("Typing text...")
pyautogui.write("Python Automation", interval=0.1)
pyautogui.press("enter")
# 2. Select text using long press (Shift + Arrow keys)
print("Selecting text...")
pyautogui.keyDown("shift")
for _ in range(3):
pyautogui.press("left")
time.sleep(0.1)
pyautogui.keyUp("shift") # Ensure the key is released
# 3. Use shortcut key (Ctrl + C)
print("Copying text...")
pyautogui.hotkey("ctrl", "c")
print("Process completed.")
except pyautogui.FailSafeException:
print("Stopped by Fail-Safe.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
automate_text_editing()
Customization Points
Parameter Settings
The following parameters are used to control the behavior of the write function.
| Parameter | Type | Meaning |
| message | str / list | The string to type or a list of key names to press in order. |
| interval | float | The delay (in seconds) between each key press. |
Function Usage
- pyautogui.write(message, interval): Best for typing out standard text strings.
- pyautogui.press(keys): Used for single presses of special keys like
esc,f1, orenter. - pyautogui.keyDown(key) / pyautogui.keyUp(key): Used for holding a key down (e.g., for selection). You must always pair a
keyDownwith akeyUp. - pyautogui.hotkey(key1, key2, …): Automatically handles the down and up sequence for key combinations like
ctrl+v.
Important Notes
- Language Support: PyAutoGUI does not directly support typing non-alphanumeric or multi-byte characters (like Japanese). To enter such text, copy it to the clipboard using
pyperclipand then usepyautogui.hotkey('ctrl', 'v'). - Layout Differences: Certain symbols (e.g.,
@,_) may differ depending on your keyboard layout (US vs. JIS). - Active Window: The script sends keys to the currently active window. Ensure the correct application is in the foreground.
Advanced Application
This example shows a safe way to handle modifier keys using a try...finally block. This ensures that keys like Ctrl are released even if the script encounters an error.
import pyautogui import time def safe_shortcut_execution(): “”” Safely executes a ‘Select All’ and ‘Copy’ sequence. “”” pyautogui.FAILSAFE = True time.sleep(2) print(“Executing Select All and Copy…”) try: # Hold Ctrl pyautogui.keyDown(‘ctrl’) # Press A and C pyautogui.press(‘a’) time.sleep(0.1) pyautogui.press(‘c’) except Exception as e: print(f”Error: {e}”) finally: # Always release Ctrl pyautogui.keyUp(‘ctrl’) print(“Ctrl key released safely.”) if __name__ == “__main__”: safe_shortcut_execution()
