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

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
  • multi monitor problems with FAIl-SAFE

    multi monitor problems with FAIl-SAFE

    I have three external monitors attached to my Macbook Air M1 (Ventura 13.1). The main window is the middle one and this makes it almost impossible to get the mouse in the corner of that monitor in order to trigger the fail-safe, as you normally overshoot into the next monitor.

    Fail-Safe should also trigger if the mouse position is outside of the monitor altogether.

    opened by AvdN 0
  • 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 1
  • [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
Owner
Al Sweigart
Not currently looking for employment.
Al Sweigart
Green is a clean, colorful, fast python test runner.

Green -- A clean, colorful, fast python test runner. Features Clean - Low redundancy in output. Result statistics for each test is vertically aligned.

Nathan Stocks 756 Dec 22, 2022
Scalable user load testing tool written in Python

Locust Locust is an easy to use, scriptable and scalable performance testing tool. You define the behaviour of your users in regular Python code, inst

Locust.io 20.4k Jan 8, 2023
splinter - python test framework for web applications

splinter - python tool for testing web applications splinter is an open source tool for testing web applications using Python. It lets you automate br

Cobra Team 2.6k Dec 27, 2022
Let your Python tests travel through time

FreezeGun: Let your Python tests travel through time FreezeGun is a library that allows your Python tests to travel through time by mocking the dateti

Steve Pulec 3.5k Jan 9, 2023
HTTP client mocking tool for Python - inspired by Fakeweb for Ruby

HTTPretty 1.0.5 HTTP Client mocking tool for Python created by Gabriel Falcão . It provides a full fake TCP socket module. Inspired by FakeWeb Github

Gabriel Falcão 2k Jan 6, 2023
A utility for mocking out the Python Requests library.

Responses A utility library for mocking out the requests Python library. Note Responses requires Python 2.7 or newer, and requests >= 2.0 Installing p

Sentry 3.8k Jan 2, 2023
A test fixtures replacement for Python

factory_boy factory_boy is a fixtures replacement based on thoughtbot's factory_bot. As a fixtures replacement tool, it aims to replace static, hard t

FactoryBoy project 3k Jan 5, 2023
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 871 Dec 25, 2022
Faker is a Python package that generates fake data for you.

Faker is a Python package that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in yo

Daniele Faraglia 15.2k Jan 1, 2023
Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes in a variety of languages.

Mimesis - Fake Data Generator Description Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes

Isaak Uchakaev 3.8k Jan 1, 2023
Coroutine-based concurrency library for Python

gevent Read the documentation online at http://www.gevent.org. Post issues on the bug tracker, discuss and ask open ended questions on the mailing lis

gevent 5.9k Dec 28, 2022
Radically simplified static file serving for Python web apps

WhiteNoise Radically simplified static file serving for Python web apps With a couple of lines of config WhiteNoise allows your web app to serve its o

Dave Evans 2.1k Jan 8, 2023
livereload server in python (MAINTAINERS NEEDED)

LiveReload Reload webpages on changes, without hitting refresh in your browser. Installation python-livereload is for web developers who know Python,

Hsiaoming Yang 977 Dec 14, 2022
A screamingly fast Python 2/3 WSGI server written in C.

bjoern: Fast And Ultra-Lightweight HTTP/1.1 WSGI Server A screamingly fast, ultra-lightweight WSGI server for CPython 2 and CPython 3, written in C us

Jonas Haag 2.9k Dec 21, 2022
Waitress - A WSGI server for Python 2 and 3

Waitress Waitress is a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in t

Pylons Project 1.2k Dec 30, 2022
Python HTTP Server

Python HTTP Server Preview Languange and Code Editor: How to run? Download the zip first. Open the http.py and wait 1-2 seconds. You will see __pycach

SonLyte 16 Oct 21, 2021
PyQaver is a PHP like WebServer for Python.

PyQaver is a PHP like WebServer for Python.

Dev Bash 7 Apr 25, 2022
Robyn is an async Python backend server with a runtime written in Rust, btw.

Robyn is an async Python backend server with a runtime written in Rust, btw. Python server running on top of of Rust Async RunTime. Installation

Sanskar Jethi 1.8k Dec 30, 2022
A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

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

Al Sweigart 7.6k Jan 1, 2023
A module for cross-platform control of the mouse and keyboard in python that is simple to install and use.

PyUserInput PyUserInput is a group project so we've moved the project over to a group organization: https://github.com/PyUserInput/PyUserInput . That

Paul Barton 1k Dec 27, 2022