在 Python 中读取 .lnk 文件的目标?

新手上路,请多包涵

我正在尝试从 Python 读取快捷方式 ( .lnk ) 文件的目标文件/目录。有无头痛的方法吗?规范超出了我的理解范围。我不介意使用仅限 Windows 的 API。

我的最终目标是在 Windows XP 和 Vista 上找到 "(My) Videos" 文件夹。在 XP 上,默认情况下,它位于 %HOMEPATH%\My Documents\My Videos ,在 Vista 上它是 %HOMEPATH%\Videos 。但是,用户可以重新定位此文件夹。在这种情况下, %HOMEPATH%\Videos 文件夹不再存在并被 %HOMEPATH%\Videos.lnk 替换,它指向新的 "My Videos" 我想要它的绝对位置。

原文由 Etienne Perot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

使用 Python 创建快捷方式(通过 WSH)

 import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()

使用 Python 读取快捷方式的目标(通过 WSH)

 import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)

原文由 SaoPauloooo 发布,翻译遵循 CC BY-SA 2.5 许可协议

我知道这是一个较旧的线程,但我觉得关于使用原始问题中提到的链接规范的方法的信息不多。

我的快捷目标实现无法使用 win32com 模块,经过大量搜索后,我决定自己实现。在我的限制下,似乎没有别的东西可以完成我所需要的。希望这会帮助处于相同情况的其他人。

它使用 Microsoft 为 MS-SHLLINK 提供的二进制结构。

 import struct

path = 'myfile.txt.lnk'
target = ''

with open(path, 'rb') as stream:
    content = stream.read()
    # skip first 20 bytes (HeaderSize and LinkCLSID)
    # read the LinkFlags structure (4 bytes)
    lflags = struct.unpack('I', content[0x14:0x18])[0]
    position = 0x18
    # if the HasLinkTargetIDList bit is set then skip the stored IDList
    # structure and header
    if (lflags & 0x01) == 1:
        position = struct.unpack('H', content[0x4C:0x4E])[0] + 0x4E
    last_pos = position
    position += 0x04
    # get how long the file information is (LinkInfoSize)
    length = struct.unpack('I', content[last_pos:position])[0]
    # skip 12 bytes (LinkInfoHeaderSize, LinkInfoFlags, and VolumeIDOffset)
    position += 0x0C
    # go to the LocalBasePath position
    lbpos = struct.unpack('I', content[position:position+0x04])[0]
    position = last_pos + lbpos
    # read the string at the given position of the determined length
    size= (length + last_pos) - position - 0x02
    temp = struct.unpack('c' * size, content[position:position+size])
    target = ''.join([chr(ord(a)) for a in temp])

原文由 Jared 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题