PyAutoGUI 使用介绍

  1. 1. 介绍
    目的
    PyAutoGUI 的目的是为人类的 GUI 自动化提供跨平台的 Python 模块。API 设计为尽可能简单,具有合理的默认值。

例如,以下是在 Windows,OS X 和 Linux 上将鼠标移动到屏幕中间的完整代码:

import pyautogui
screenWidth, screenHeight = pyautogui.size()
pyautogui.moveTo(screenWidth / 2, screenHeight / 2)
这就是全部。

PyAutoGUI 可以模拟移动鼠标,单击鼠标,用鼠标拖动,按键,按住键,然后按键盘热键组合。

示例

import pyautogui
screenWidth, screenHeight = pyautogui.size()
currentMouseX, currentMouseY = pyautogui.position()
pyautogui.moveTo(100, 150)
pyautogui.click()
pyautogui.moveRel(None, 10) # move mouse 10 pixels down
pyautogui.doubleClick()
pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # use tweening/easing function to move mouse over 2 seconds.
pyautogui.typewrite(‘Hello world!’, interval=0.25) # type with quarter-second pause in between each key
pyautogui.press(‘esc’)
pyautogui.keyDown(‘shift’)
pyautogui.press([‘left’, ‘left’, ‘left’, ‘left’, ‘left’, ‘left’])
pyautogui.keyUp(‘shift’)
pyautogui.hotkey(‘ctrl’, ‘c’)
此示例在 MS Paint(或任何图形绘制程序)中将鼠标拖动为方形螺旋形状:

distance = 200
while distance > 0:
pyautogui.dragRel(distance, 0, duration=0.5) # move right
distance -= 5
pyautogui.dragRel(0, distance, duration=0.5) # move down
pyautogui.dragRel(-distance, 0, duration=0.5) # move left
distance -= 5
pyautogui.dragRel(0, -distance, duration=0.5) # move up

依赖
在 Windows 上,PyAutoGUI 没有依赖关系(除了 Pillow 和其他一些模块,它们是由 pip 和 PyAutoGUI 一起安装的)。它并不需要 pywin32,因为它使用了 Python 的安装模块 ctypes 的模块。

在 OS X 上,PyAutoGUI 需要为 AppKit 和 Quartz 模块安装 PyObjC。PyPI 上的模块名称安装是 pyobjc-core 和 pyobjc(按顺序)。

在 Linux 上,PyAutoGUI 需要 python-xlib(对于 Python 2)或 python3-Xlib(对于 Python 3)模块安装。

失败保险
_images / sorcerers_apprentice_brooms.png
就像 Sorcerer’s Apprentice 的魔法扫帚一样,用水冲洗(然后过度填充)浴缸,你的程序可能会失控(即使它遵循你的指示),需要停止。如果鼠标自行移动,这可能很难做到,这使您无法单击程序窗口将其关闭。

作为安全功能,默认情况下启用故障安全功能。当 PyAutoGUI 功能将引发如果鼠标光标在屏幕的左上角。如果失去控制并需要停止当前的 PyAutoGUI 功能,请继续向上和向左移动鼠标光标。要禁用此功能,请设置为:pyautogui.FAILSAFE = Truepyautogui.FailSafeExceptionFAILSAFEFalse

import pyautogui
pyautogui.FAILSAFE = False # disables the fail-safe
您可以通过将 pyautogui.PAUSE 变量设置为要暂停的秒数的浮点数或整数值,在所有 PyAutoGUI 函数之后添加延迟。默认情况下,暂停设置为 0.1 秒。这在与其他应用程序交互时非常有用,因此 PyAutoGUI 对它们的移动速度不会太快。例如:

import pyautogui
pyautogui.PAUSE = 2.5
pyautogui.moveTo(100, 100); pyautogui.click() # there will be a two and a half second pause after moving and another after the click
所有 PyAutoGUI 函数都将阻塞,直到它们完成。(在路线图中添加一个可选的非阻塞方式来调用这些函数。)

建议使用 FAILSAFE 并设置 PAUSE。