A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

Related tags

Testing pyautogui
Overview

PyAutoGUI

PyAutoGUI is a cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

pip install pyautogui

Full documentation available at https://pyautogui.readthedocs.org

Simplified Chinese documentation available at https://muxuezi.github.io/posts/doc-pyautogui.html

Source code available at https://github.com/asweigart/pyautogui

If you need help installing Python, visit https://installpython3.com/

Dependencies

PyAutoGUI supports Python 2 and 3. If you are installing PyAutoGUI from PyPI using pip:

Windows has no dependencies. The Win32 extensions do not need to be installed.

macOS needs the rubicon-objc module installed (in that order).

Linux needs the python3-xlib (or python-xlib for Python 2) module installed.

Pillow needs to be installed, and on Linux you may need to install additional libraries to make sure Pillow's PNG/JPEG works correctly. See:

https://stackoverflow.com/questions/7648200/pip-install-pil-e-tickets-1-no-jpeg-png-support

http://ubuntuforums.org/showthread.php?t=1751455

If you want to do development and contribute to PyAutoGUI, you will need to install these modules from PyPI:

  • pyscreeze
  • pymsgbox
  • pytweening

Example Usage

Keyboard and Mouse Control

The x, y coordinates used by PyAutoGUI has the 0, 0 origin coordinates in the top left corner of the screen. The x coordinates increase going to the right (just as in mathematics) but the y coordinates increase going down (the opposite of mathematics). On a screen that is 1920 x 1080 pixels in size, coordinates 0, 0 are for the top left while 1919, 1079 is for the bottom right.

Currently, PyAutoGUI only works on the primary monitor. PyAutoGUI isn't reliable for the screen of a second monitor (the mouse functions may or may not work on multi-monitor setups depending on your operating system and version).

All keyboard presses done by PyAutoGUI are sent to the window that currently has focus, as if you had pressed the physical keyboard key.

    >>> import pyautogui
    >>> screenWidth, screenHeight = pyautogui.size() # Returns two integers, the width and height of the screen. (The primary monitor, in multi-monitor setups.)
    >>> currentMouseX, currentMouseY = pyautogui.position() # Returns two integers, the x and y of the mouse cursor's current position.
    >>> pyautogui.moveTo(100, 150) # Move the mouse to the x, y coordinates 100, 150.
    >>> pyautogui.click() # Click the mouse at its current location.
    >>> pyautogui.click(200, 220) # Click the mouse at the x, y coordinates 200, 220.
    >>> pyautogui.move(None, 10)  # Move mouse 10 pixels down, that is, move the mouse relative to its current position.
    >>> pyautogui.doubleClick() # Double click the mouse at the
    >>> pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # Use tweening/easing function to move mouse over 2 seconds.
    >>> pyautogui.write('Hello world!', interval=0.25)  # Type with quarter-second pause in between each key.
    >>> pyautogui.press('esc') # Simulate pressing the Escape key.
    >>> pyautogui.keyDown('shift')
    >>> pyautogui.write(['left', 'left', 'left', 'left', 'left', 'left'])
    >>> pyautogui.keyUp('shift')
    >>> pyautogui.hotkey('ctrl', 'c')

Display Message Boxes

    >>> import pyautogui
    >>> pyautogui.alert('This is an alert box.')
    'OK'
    >>> pyautogui.confirm('Shall I proceed?')
    'Cancel'
    >>> pyautogui.confirm('Enter option.', buttons=['A', 'B', 'C'])
    'B'
    >>> pyautogui.prompt('What is your name?')
    'Al'
    >>> pyautogui.password('Enter password (text will be hidden)')
    'swordfish'

Screenshot Functions

(PyAutoGUI uses Pillow for image-related features.)

    >>> import pyautogui
    >>> im1 = pyautogui.screenshot()
    >>> im1.save('my_screenshot.png')
    >>> im2 = pyautogui.screenshot('my_screenshot2.png')

You can also locate where an image is on the screen:

    >>> import pyautogui
    >>> button7location = pyautogui.locateOnScreen('button.png') # returns (left, top, width, height) of matching region
    >>> button7location
    (1416, 562, 50, 41)
    >>> buttonx, buttony = pyautogui.center(button7location)
    >>> buttonx, buttony
    (1441, 582)
    >>> pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found

The locateCenterOnScreen() function returns the center of this match region:

    >>> import pyautogui
    >>> buttonx, buttony = pyautogui.locateCenterOnScreen('button.png') # returns (x, y) of matching region
    >>> buttonx, buttony
    (1441, 582)
    >>> pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found

How Does PyAutoGUI Work?

The three major operating systems (Windows, macOS, and Linux) each have different ways to programmatically control the mouse and keyboard. This can often involve confusing, obscure, and deeply technical details. The job of PyAutoGUI is to hide all of this complexity behind a simple API.

  • On Windows, PyAutoGUI accesses the Windows API (also called the WinAPI or win32 API) through the built-in ctypes module. The nicewin module at https://github.com/asweigart/nicewin provides a demonstration for how Windows API calls can be made through Python.

  • On macOS, PyAutoGUI uses the rubicon-objc module to access the Cocoa API.

  • On Linux, PyAutoGUI uses the Xlib module to access the X11 or X Window System.

Comments
  • Pyautogui doesn't seem to work on macOS Mojave

    Pyautogui doesn't seem to work on macOS Mojave

    I recently updated to macOS Mojave (10.14 Beta). Commands like pyautogui.moveTo(1027,73), pyautogui.click(1027,73), etc. don't seem to work at all. Neither any error messages are thrown nor do the method calls work. pyautogui worked perfectly on macOS High Sierra.

    opened by chaityacshah 19
  • possibility to look for multiple images in one screen shot

    possibility to look for multiple images in one screen shot

    Hi! currently only function locateAllOnScreen exists, which looks for all instances of single "needle".

    If one needs to check for multiple "needles" on the same screen, it means repeating screen capture for as many different needles and required (locateOnScreen) . Would it be possible to fix the screenshot somehow and then look for the "needles"? Or one shuold turn to Pillow for such job?

    opened by Jancs-E 13
  • Sending

    Sending "Ctrl-C" hotkey combination does not work

    I've been searching for a solution to this for several days, but am beginning to wonder if I'm just looking at a bug.

    I have a script that needs to copy to the clipboard using Ctrl + C, but somehow sending this key combination has lost functionality in pyautogui.

    There is no exception thrown, and it appears everything is executing as it should be. However, the desired text is not copied to the clipboard. Copying the text manually using Ctrl + C (on my actual keyboard) does cause the desired text to be copied. However, when running pyautogui the clipboard remains unchanged.

    I found this question on Stack Overflow that verifies the issue: http://stackoverflow.com/questions/38899566/python-pyautogui-and-ctrl-c?newreg=4a6bdd511c314b129438d6d79f427600

    I am also running Windows 7 and Python 3.5, as is Todd Lewden, the author of the Stack Overflow question.

    The "Cheat Sheet" on Read the Docs indicates that this functionality should be present in pyautogui:

    Keyboard hotkeys like Ctrl-S or Ctrl-Shift-1 can be done by passing a list of key names to hotkey():

    pyautogui.hotkey('ctrl', 'c') # ctrl-c to copy pyautogui.hotkey('ctrl', 'v') # ctrl-v to paste

    I'm not sure at what point sending the "Ctrl + C" combination became broken, but it looks like it worked at some point, according to the above reference to the documentation.

    I had a thought that perhaps it has to do with "Ctrl + C" being a Python keyboard interrupt, but I don't know that that is the case. If it were, Python should come to a screeching halt when the Ctrl + C is sent. It appears to execute without error, except that it doesn't work.

    opened by AWPelican 13
  • _locateAll_python() got an unexpected keyword argument 'confidence'

    _locateAll_python() got an unexpected keyword argument 'confidence'

    When i use pyautogui.locateCenterOnScreen("a.png", confidence=.9) on my PC it works just fine, but when i use the exact same command on my laptop it won't work and gives the error in the title. I did pip install pyautogui on both machines, does anybody know how to fix that?

    opened by aj22r 11
  • KeyError: 'DISPLAY' when installing pyautogui

    KeyError: 'DISPLAY' when installing pyautogui

    When I tried to install pyautogui with sudo pip3 install pyautogui I get the error info

    pi@raspberrypi:~/Desktop/test/c_test $ sudo pip3 install pyautogui Downloading/unpacking pyautogui Downloading PyAutoGUI-0.9.36.tar.gz (46kB): 46kB downloaded Running setup.py (path:/tmp/pip-build-tbxln81q/pyautogui/setup.py) egg_info for package pyautogui Traceback (most recent call last): File "", line 17, in File "/tmp/pip-build-tbxln81q/pyautogui/setup.py", line 6, in version=import('pyautogui').version, File "/tmp/pip-build-tbxln81q/pyautogui/pyautogui/init.py", line 115, in from . import _pyautogui_x11 as platformModule File "/tmp/pip-build-tbxln81q/pyautogui/pyautogui/_pyautogui_x11.py", line 160, in _display = Display(os.environ['DISPLAY']) File "/usr/lib/python3.4/os.py", line 633, in getitem raise KeyError(key) from None KeyError: 'DISPLAY' Complete output from command python setup.py egg_info: Traceback (most recent call last):

    File "", line 17, in

    File "/tmp/pip-build-tbxln81q/pyautogui/setup.py", line 6, in

    version=__import__('pyautogui').__version__,
    

    File "/tmp/pip-build-tbxln81q/pyautogui/pyautogui/init.py", line 115, in

    from . import _pyautogui_x11 as platformModule
    

    File "/tmp/pip-build-tbxln81q/pyautogui/pyautogui/_pyautogui_x11.py", line 160, in

    _display = Display(os.environ['DISPLAY'])
    

    File "/usr/lib/python3.4/os.py", line 633, in getitem

    raise KeyError(key) from None
    

    KeyError: 'DISPLAY'


    Cleaning up... Command python setup.py egg_info failed with error code 1 in /tmp/pip-build-tbxln81q/pyautogui Storing debug log for failure in /root/.pip/pip.log

    I followed the install steps listed in the Docs(http://pyautogui.readthedocs.io/en/latest/install.html). Do anyone know why this happens and how to fix it? Thank you so much.

    opened by curkychen 10
  • Tweening not working as expected (win 7, Python)

    Tweening not working as expected (win 7, Python)

    Hello,

    Tween was not working for me and found that the value tween function was receiving was not within the 0..1 range.

    I have not looked further for the why and quickly modified the code to this:

    if duration <= MINIMUM_DURATION:
        print("duration check")   
        if moveOrDrag == 'move':
            print("move") 
            platformModule._moveTo(x, y)
        else:
            print("drag") 
            platformModule._dragTo(x, y, button)
        return
    
    tweenfinished = False
    starttime = time.time()
    
    while(tweenfinished == False):
        _failSafeCheck()
        elapsedtime = time.time() - starttime
    
        tweenvalue = min(1, max(0, float(elapsedtime) / float(duration)))
    
        pointOnLine = tween(tweenvalue) # range 0 / 1
        tweenX, tweenY = getPointOnLine(startx, starty, x, y, pointOnLine)
        tweenX, tweenY = int(tweenX), int(tweenY)
    
        if moveOrDrag == 'move':
            platformModule._moveTo(tweenX, tweenY)
        else:
            # only OS X needs the drag event specifically
            platformModule._dragTo(tweenX, tweenY, button)
        if (elapsedtime < duration) :
            time.sleep(0.001)
        else :
            tweenfinished = True
    
    # TODO: Test range. Should not be necessary with previous change??        
    # Ensure that no matter what the tween function returns, the mouse ends up
    # at the final destination.
    #if moveOrDrag == 'move':
    #    platformModule._moveTo(x, y)
    #else:
    #    platformModule._dragTo(x, y, button)
    

    This would probably require a second look and more test before such fix could be submited as a pull request but it's working well for what I need (and I'm a little bit pressured by time).

    Thanks for the great library!

    Eric

    opened by bleuetnoir 10
  • feature request: tolerance for locate on screen

    feature request: tolerance for locate on screen

    (Picking up from the tail end of discussion on #4)

    A tolerance for locating on screen would be of interest to several people.

    Possible easy solution: expose the "confidence" parameter, allowing people to locate with reduced confidence ( = more tolerance for mismatches)

    opened by jeremygray 9
  • Some characters are not working with German layout keyboard

    Some characters are not working with German layout keyboard

    I do have a strange problem, using a German keyboard layout.

    pyautogui.typewrite("!"#$%&()+H")
    !"'$%&()
    *H

    Which means '#' results in an ' and '+' results in an *. This is quite strange, as all other characters seem to work.

    The software, I'm targeting to, is very dumb. It does not accept 'CTRL'+'V' nor 'ALT'+'35' in it's text fields, so I really have to simmulate single keystrokes. Unfortunately I do need the Hash # sign to trigger some actions.

    OS: Windows 8; Python: V3.4.3

    Are there any ideas for a work around? Anny suggestions appreciated!

    opened by E2w4UmWh 8
  • macOS - `locateOnScreen()` coordinates are off by a factor of 2

    macOS - `locateOnScreen()` coordinates are off by a factor of 2

    locateOnScreen() works perfectly on Ubuntu Linux but on MacOS it always adds a varying offset. As X increases, the coordinates returned by locateOnScreen() increases by a certain ratio, similar for Y but increases slightly less.

    Doesn't matter how many desktop/workspaces I have active, the result is the same.

    opened by rez1-inf 7
  • pyautogui.pixel() intermittent error: windll.user32.ReleaseDC failed : return 0

    pyautogui.pixel() intermittent error: windll.user32.ReleaseDC failed : return 0

    I sporadically get the following error when trying to use pyautogui.pixel() on Windows 10. Here's on a fresh command line interface. It failed the second time, but ran easily 10 in a row after and did not fail.

    Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import pyautogui
    >>> pyautogui.pixel(0, 0)
    (240, 240, 240)
    >>> pyautogui.pixel(0, 0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\a1rwhzz\AppData\Roaming\Python\Python39\site-packages\pyscreeze\__init__.py", line 613, in pixel
        return (r, g, b)
      File "C:\Users\a1rwhzz\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 124, in __exit__
        next(self.gen)
      File "C:\Users\a1rwhzz\AppData\Roaming\Python\Python39\site-packages\pyscreeze\__init__.py", line 122, in __win32_openDC
        raise WindowsError("windll.user32.ReleaseDC failed : return 0")
    OSError: windll.user32.ReleaseDC failed : return 0
    >>> pyautogui.pixel(0, 0)
    (240, 240, 240)
    >>> pyautogui.pixel(0, 0)
    (240, 240, 240)
    >>> pyautogui.pixel(0, 0)
    ...
    

    I'm unable to reliably reproduce it, though it seems that many others have gotten the error (and sometimes related to other functions, not just pixel()). Sadly, many of the suggestions just say to download to 3.7. I'm surprised it's not coming up more here; he closest I could find was #229 which is about some type of limit, which doesn't seem to be the cause here.

    In my actual environment (a jupyter notebook) it seems to fail more often, but is unpredictable. Just re-running the cell often works the next time.

    Is there a way to better track this down? Obviously if one is automating something, an unpredictable error that breaks flow is a pretty huge hurdle! Happy to provide more information or try any suggestions in order to assist.

    Edit: fixed link issues

    opened by jwhendy 7
  • Add menu key

    Add menu key

    This is a feature request, but i could find how I could tag it as such.

    Menu key would be quite useful for GUI automation I believe. Luckily I found a workaround: it turns out at least some applications support Shift + F10 as an alternative.

    opened by i-need-to-tell-you-something 7
  • Pyautogui locate doesn't work on mac

    Pyautogui locate doesn't work on mac

    Hi guys

    I was using windows in my job, but now I start with a Mac pro. The function locate doesn't work at all. When I tried to use mouseinfo it returns NA_on_mac0S. How can I fix that?

    opened by Luis-Felipe-Franca 0
  • [Question] Why is pyautogui mousemovement not recognised by Win10?

    [Question] Why is pyautogui mousemovement not recognised by Win10?

    Hi,

    I used AutoHotKey and the function mousemove() for a while. With hthis code, my windows did not lock and MS Teams e.g. showed me as active:

    Loop{ MouseMove, 10, 5, ,R sleep 300000 }

    I tried to reproduce this with pyautogui and this code:

    `import pyautogui as py import time

    while True: py.moveRel(5,10) time.sleep(300)`

    I see the mouse moving, but MS Teams shows me as inactive after 5 minutes and after 10 minuters my monitor turns off.

    So what´s wrong here?

    opened by Tech4Ever 2
  • [Question] Does pyautogui work with wayland?

    [Question] Does pyautogui work with wayland?

    I am using imagehorizonlibrary that uses pyautogui, when I am using Ubuntu 22.04 with the wayland windowing system all I get is image not found and screen shots that are completely black.

    So I am wondering if pyautogui supports wayland?

    • If not:
      • can you update the documentation to mention it's not yet supported
      • is there a plan to support wayland going forward?
    opened by damies13 0
  • Can't Take Screenshot (Unable to locate Pillow)

    Can't Take Screenshot (Unable to locate Pillow)

    Pyautogui cannot locate Pillow even though it's installed. It throws an error saying:

    raise PyScreezeException('The Pillow package is required to use this function.')
    pyscreeze.PyScreezeException: The Pillow package is required to use this function.
    

    image

    opened by javaisgarbage 0
Owner
Al Sweigart
Not currently looking for employment.
Al Sweigart
Automated mouse clicker script using PyAutoGUI and Typer.

clickpy Automated mouse clicker script using PyAutoGUI and Typer. This app will randomly click your mouse between 1 second and 3 minutes, to prevent y

Joe Fitzgibbons 0 Dec 1, 2021
Selenium-python but lighter: Helium is the best Python library for web automation.

Selenium-python but lighter: Helium Selenium-python is great for web automation. Helium makes it easier to use. For example: Under the hood, Helium fo

Michael Herrmann 3.2k Dec 31, 2022
✅ Python web automation and testing. 🚀 Fast, easy, reliable. 💠

Build fast, reliable, end-to-end tests. SeleniumBase is a Python framework for web automation, end-to-end testing, and more. Tests are run with "pytes

SeleniumBase 3k Jan 4, 2023
Flexible test automation for Python

Nox - Flexible test automation for Python nox is a command-line tool that automates testing in multiple Python environments, similar to tox. Unlike to

Stargirl Flowers 941 Jan 3, 2023
Python version of the Playwright testing and automation library.

?? Playwright for Python Docs | API Playwright is a Python library to automate Chromium, Firefox and WebKit browsers with a single API. Playwright del

Microsoft 7.8k Jan 2, 2023
Akulaku Create NewProduct Automation using Selenium Python

Akulaku-Create-NewProduct-Automation Akulaku Create NewProduct Automation using Selenium Python Usage: 1. Install Python 3.9 2. Open CMD on Bot Folde

Rahul Joshua Damanik 1 Nov 22, 2021
Yet another python home automation project. Because a smart light is more than just on or off

Automate home Yet another home automation project because a smart light is more than just on or off. Overview When talking about home automation there

Maja Massarini 62 Oct 10, 2022
Generic automation framework for acceptance testing and RPA

Robot Framework Introduction Installation Example Usage Documentation Support and contact Contributing License Introduction Robot Framework is a gener

Robot Framework 7.7k Jan 7, 2023
A folder automation made using Watch-dog, it only works in linux for now but I assume, it will be adaptable to mac and PC as well

folder-automation A folder automation made using Watch-dog, it only works in linux for now but I assume, it will be adaptable to mac and PC as well Th

Parag Jyoti Paul 31 May 28, 2021
A browser automation framework and ecosystem.

Selenium Selenium is an umbrella project encapsulating a variety of tools and libraries enabling web browser automation. Selenium specifically provide

Selenium 25.5k Jan 1, 2023
Headless chrome/chromium automation library (unofficial port of puppeteer)

Pyppeteer Pyppeteer has moved to pyppeteer/pyppeteer Unofficial Python port of puppeteer JavaScript (headless) chrome/chromium browser automation libr

miyakogi 3.5k Dec 30, 2022
A complete test automation tool

Golem - Test Automation Golem is a test framework and a complete tool for browser automation. Tests can be written with code in Python, codeless using

null 486 Dec 30, 2022
Integration layer between Requests and Selenium for automation of web actions.

Requestium is a Python library that merges the power of Requests, Selenium, and Parsel into a single integrated tool for automatizing web actions. The

Tryolabs 1.7k Dec 27, 2022
Command line driven CI frontend and development task automation tool.

tox automation project Command line driven CI frontend and development task automation tool At its core tox provides a convenient way to run arbitrary

tox development team 3.1k Jan 4, 2023
Network automation lab using nornir, scrapli, and containerlab with Arista EOS

nornir-scrapli-eos-lab Network automation lab using nornir, scrapli, and containerlab with Arista EOS. Objectives Deploy base configs to 4xArista devi

Vireak Ouk 13 Jul 7, 2022
Nokia SR OS automation

Nokia SR OS automation Nokia is one of the biggest vendors of the telecommunication equipment, which is very popular in the Service Provider segment.

Karneliuk.com 7 Jul 23, 2022
buX Course Enrollment Automation

buX automation BRACU - buX course enrollment automation Features: Automatically enroll into multiple courses at a time. Find courses just entering cou

Mohammad Shakib 1 Oct 6, 2022
Android automation project with pytest+appium

Android automation project with pytest+appium

null 1 Oct 28, 2021
Public repo for automation scripts

Script_Quickies Public repo for automation scripts Dependencies Chrome webdriver .exe (make sure it matches the version of chrome you are using) Selen

CHR-onicles 1 Nov 4, 2021