Python Script Failing to Open Firefox.lnk file on Desktop Path

Question:

TLDR; I have a python script that uses autopygui to click on a file and open it, but it does not work with lnk files located in the same path.

I have a little script using pyautogui to screenshot a desktop icon and save it as a png image on the desktop and doubleclick it to open that image. This works perfect.

However..

I tried implementing the same script on an existing Firefox.lnk shortcut and it fails with the following error:

locateOnScreen Error

Things I have tried:

  1. Running VS code as admin.

  2. locateOnCenterScreen and locateOnScreen.

  3. I have tried others, but I’m blanking because I have tried everything I can think of.

It should open my Firefox.lnk shortcut up, it does not. It only works on png file.

Asked By: user21062978

||

Answers:

It’s because the locateOnScreen(...) function only accepts paths to image files, and .lnk files are not image files. If you manually took a screenshot of the Firefox icon on your desktop, saved it as a PNG file, and passed that to your script, it would open fine.

If you want to launch a program using a .lnk file from Python, you don’t need pyautogui at all. Consider using os.startfile(...) instead.

Answered By: wallefan

You should put the path of png file in locateCenterOnScreen(...) function instead.

Please also make sure you minimize all active windows so that pyautogui could locate your Firefox short icon.

import pyautogui
pyautogui.hotkey('winleft','d')
icon_location = pyautogui.locateCenterOnScreen('.../FireFox_icon_screenshot.png', confidence=0.9)
pyautogui.moveTo(icon_location)
pyautogui.click(clicks=2)
Answered By: Tony Wu