You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyAutoGui通过Popen启动Putty时locateOnScreen返回None报错问题

错误原因

调用Popen('putty.exe')后程序没有等待PuTTY窗口完成加载渲染,就立刻执行图像匹配操作,此时屏幕上还不存在目标元素,locateOnScreen会返回None,对None调用center()方法就触发了类型报错。手动启动PuTTY时窗口已经加载完成,所以匹配可以正常生效。

解决方案

  • 启动PuTTY后增加等待逻辑,不要立即执行图像匹配。可先用pyautogui.sleep(3)做固定时长等待,更稳妥的方案是循环检测目标元素,超时后抛出异常中断流程。
  • 补充返回值校验逻辑,每次调用locateOnScreen后先判断返回值是否为None,确认找到目标元素后再执行后续坐标计算、点击操作,避免空值异常。
  • 确认PuTTY程序路径正确,如果putty.exe不在系统环境变量PATH中,需要给Popen传入PuTTY的完整绝对路径。
  • 检查匹配用的png图片路径是否正确,你当前代码中定义了log_path但没有用来拼接图片路径,可能会出现图片读取失败的问题。
  • 如果使用高DPI屏幕,可额外开启PyAutoGUI的DPI适配,避免图像匹配精度下降。

修复后参考代码

import pyautogui
import os
from subprocess import Popen
import time

home = os.path.expanduser('~')
corrected_path = home.replace(os.sep, '\\')
log_path = corrected_path + '\\PyAutoGuiPNGs\\'
pyautogui.PAUSE = 1 # 全局设置操作间隔,无需单次重复定义

# 若putty不在系统PATH中,此处替换为putty的完整绝对路径
Popen('putty.exe')

# 循环等待已保存会话元素加载,最多等待10秒
max_wait = 10
start_time = time.time()
saved_session = None
while time.time() - start_time < max_wait:
    saved_session = pyautogui.locateOnScreen(f"{log_path}saved_session.png", grayscale=True, confidence=0.5)
    if saved_session is not None:
        break
    time.sleep(0.5)

if saved_session is None:
    raise Exception("超时未找到已保存会话匹配元素")

session_center = pyautogui.center(saved_session)
pyautogui.moveTo(session_center)
pyautogui.click()

pyautogui.write('router')

# 等待load按钮加载
max_wait = 5
start_time = time.time()
load = None
while time.time() - start_time < max_wait:
    load = pyautogui.locateOnScreen(f"{log_path}load.png", grayscale=True, confidence=0.5)
    if load is not None:
        break
    time.sleep(0.5)

if load is None:
    raise Exception("超时未找到load按钮")

load_center = pyautogui.center(load)
pyautogui.moveTo(load_center)
pyautogui.click()

# 等待open按钮加载
max_wait = 5
start_time = time.time()
open_button = None
while time.time() - start_time < max_wait:
    open_button = pyautogui.locateOnScreen(f"{log_path}open.png", grayscale=True, confidence=0.5)
    if open_button is not None:
        break
    time.sleep(0.5)

if open_button is None:
    raise Exception("超时未找到open按钮")

open_center = pyautogui.center(open_button)
pyautogui.moveTo(open_center)
pyautogui.click()

内容的提问来源于stack exchange,提问作者dtrinh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:42:00