使用 pyautogui 自动化鼠标和键盘的更好方法
better way to automate mouse&keyboard using pyautogui
我使用 pyautogui
编写了一个脚本,它应该启动一个程序(一个 IDE)然后开始使用它。
这是目前的脚本:
#! python3
# mouseNow.py - Displays the mouse cursor's current position.
import pyautogui, sys, subprocess
from time import sleep
x,y = 1100,550
subprocess.call([r'C:\...exe', arg1, arg2])
pyautogui.click(x,y)
sleep(5) # 2 sec should suffice but this is for safety
pyautogui.typewrite(my_string)
pyautogui.press('enter')
这很好用,但我想便携。 x,y
值由启动程序后程序提示出现在屏幕上的位置决定,但我认为这不可移植。有没有办法不用给const参数就可以把鼠标指向提示呢?像 move_mouse_to_window_of_this_process_after_starting_it()
此外,我使用sleep()
所以我会在window出现后将数据写入window,但我想这不是一个好方法(有些 PC 会 运行 这么慢,我猜),那么有没有办法知道提示出现的时间然后执行 pyautogui.typewrite(my_string)
?
编辑: 我找到了 move_mouse_to_window_of_this_process_after_starting_it()
的简单解决方案
:
>>> pyautogui.hotkey('alt', 'tab')
您与 .exe 交互的方式不包括坐标或盲击(Tab、Tab、Enter 等)的替代方法。
如果应用程序有 API,您可以通过编程方式与其交互。
如果不是,您只能尝试匹配 x 屏幕分辨率的位置,并且只有在 Fullscreen/windowed 全屏中使用 GUI 时才会这样做。
如果您需要可移植且可靠的解决方案,则必须找到一个支持可访问性技术的库以通过文本访问 GUI 元素。基本技术是:
- Win32 API、MS UI 自动化 (Windows)
- AT-SPI (Linux)
- Apple 辅助功能API (MacOS)
有几个开源 GUI 自动化库支持其中一些技术(通常是 1 或 2)。 Python 解决方案:
- pywinauto on Windows (both Win32 API & MS UIA, see Getting Started Guide)
- pyatspi2 在 Linux
- pyatom 在 MacOS 上
还有关于硬睡眠与灵活等待。
尽情享受吧! :)
我使用 pyautogui
编写了一个脚本,它应该启动一个程序(一个 IDE)然后开始使用它。
这是目前的脚本:
#! python3
# mouseNow.py - Displays the mouse cursor's current position.
import pyautogui, sys, subprocess
from time import sleep
x,y = 1100,550
subprocess.call([r'C:\...exe', arg1, arg2])
pyautogui.click(x,y)
sleep(5) # 2 sec should suffice but this is for safety
pyautogui.typewrite(my_string)
pyautogui.press('enter')
这很好用,但我想便携。 x,y
值由启动程序后程序提示出现在屏幕上的位置决定,但我认为这不可移植。有没有办法不用给const参数就可以把鼠标指向提示呢?像 move_mouse_to_window_of_this_process_after_starting_it()
此外,我使用sleep()
所以我会在window出现后将数据写入window,但我想这不是一个好方法(有些 PC 会 运行 这么慢,我猜),那么有没有办法知道提示出现的时间然后执行 pyautogui.typewrite(my_string)
?
编辑: 我找到了 move_mouse_to_window_of_this_process_after_starting_it()
的简单解决方案
:
>>> pyautogui.hotkey('alt', 'tab')
您与 .exe 交互的方式不包括坐标或盲击(Tab、Tab、Enter 等)的替代方法。
如果应用程序有 API,您可以通过编程方式与其交互。 如果不是,您只能尝试匹配 x 屏幕分辨率的位置,并且只有在 Fullscreen/windowed 全屏中使用 GUI 时才会这样做。
如果您需要可移植且可靠的解决方案,则必须找到一个支持可访问性技术的库以通过文本访问 GUI 元素。基本技术是:
- Win32 API、MS UI 自动化 (Windows)
- AT-SPI (Linux)
- Apple 辅助功能API (MacOS)
有几个开源 GUI 自动化库支持其中一些技术(通常是 1 或 2)。 Python 解决方案:
- pywinauto on Windows (both Win32 API & MS UIA, see Getting Started Guide)
- pyatspi2 在 Linux
- pyatom 在 MacOS 上
还有
尽情享受吧! :)