Create Windows Shortcut

2023-01-13

說明如何使用 Python 產生 Windows 的雙向捷徑 (來源與目標互相指向的捷徑)

logo

說明

需要先使用 pip 進行 packages 的安裝:

pip install pywin32
pip install winshell

Create & Read Lnk

利用 WScript.Shell 進行 Lnk 的建立:

shell = Dispatch('WScript.Shell')

shortcut = shell.CreateShortCut(r'D:\Temp\lnk.lnk')
shortcut.Targetpath = r'D:\SomeFolders\'
shortcut.save()

如果要讀取 Lnk 的內容,可以同樣使用 WScript.Shell 操作:

shell = Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(r'D:\Temp\lnk.lnk')
print(shortcut.Targetpath)

完整程式碼

import os, winshell
import uuid
from win32com.client import Dispatch
from colorama import Style, Fore, Back

class Lnk:
    def __init__(self, lnkName, workingDirectory, target, shell):
        self.lnkName = lnkName
        self.workingDirectory = workingDirectory
        self.target = target
        self.shell = shell

    def _get_location(self):
        return os.path.join(self.workingDirectory, self.lnkName)
    
    location = property(
        fget = _get_location,
        doc = "The Location property (lnk parent folder + lnk fileName)."
    )        

    def Save(self):
        """Create Lnk File"""
        shortcut = self.shell.CreateShortCut(self.location)
        shortcut.Targetpath = self.target
        shortcut.save()

def main():
    os.system("cls")

    currentPath = input(Fore.LIGHTGREEN_EX + 'current path> ' + Style.RESET_ALL)
    attachPath = r'D:\WindowsLnk'

    guid = str(uuid.uuid4())
    lnkName = f'attatch-{guid[:3]}.lnk'
    target = os.path.join(attachPath, guid)

    # CREATE ATTACH FOLDER
    os.mkdir(target)

    shell = Dispatch('WScript.Shell')
    lnkToAttach = Lnk(lnkName, currentPath, target, shell)
    lnkToAttach.Save()

    print(Fore.LIGHTBLUE_EX + f'{lnkToAttach.location}' + Style.RESET_ALL)

    lnkToOrigin = Lnk('origin.lnk', target, currentPath, shell)
    lnkToOrigin.Save()

main()

參考資料

create a shortcut(.lnk) of file in windows with python3 | stackoverflow