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

2024-06-07 08:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从Python中读取快捷方式(.lnk)文件的目标文件/目录。有没有头痛的方法呢?这个.lnk spec [PDF]在我头上。 我不介意只使用Windows的api。

我的最终目标是在Windows XP和Vista上找到"(My) Videos"文件夹。在XP上,默认是在%HOMEPATH%\My Documents\My Videos,在Vista上是%HOMEPATH%\Videos。但是,用户可以重新定位此文件夹。在本例中,%HOMEPATH%\Videos文件夹不再存在,取而代之的是指向新的"My Videos"文件夹的%HOMEPATH%\Videos.lnk。我想要它的绝对位置。


Tags: 文件方法目录文件夹目标mywindowsvideos
3条回答

基本上是直接调用Windows API。以下是在谷歌搜索后发现的一个很好的例子:

import os, sys
import pythoncom
from win32com.shell import shell, shellcon

shortcut = pythoncom.CoCreateInstance (
  shell.CLSID_ShellLink,
  None,
  pythoncom.CLSCTX_INPROC_SERVER,
  shell.IID_IShellLink
)
desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)
shortcut_path = os.path.join (desktop_path, "python.lnk")
persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
persist_file.Load (shortcut_path)

shortcut.SetDescription ("Updated Python %s" % sys.version)
mydocs_path = shell.SHGetFolderPath (0, shellcon.CSIDL_PERSONAL, 0, 0)
shortcut.SetWorkingDirectory (mydocs_path)

persist_file.Save (shortcut_path, 0)

这是来自http://timgolden.me.uk/python/win32_how_do_i/create-a-shortcut.html

您可以在“python ishelllink”中搜索其他示例。

此外,API引用也有帮助:http://msdn.microsoft.com/en-us/library/bb774950(VS.85).aspx

使用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)

或者,您可以尝试使用SHGetFolderPath()。下面的代码可能可以工作,但是我现在不在Windows机器上,所以无法测试它。

import ctypes

shell32 = ctypes.windll.shell32

# allocate MAX_PATH bytes in buffer
video_folder_path = ctypes.create_string_buffer(260)

# 0xE is CSIDL_MYVIDEO
# 0 is SHGFP_TYPE_CURRENT
# If you want a Unicode path, use SHGetFolderPathW instead
if shell32.SHGetFolderPathA(None, 0xE, None, 0, video_folder_path) >= 0:
    # success, video_folder_path now contains the correct path
else:
    # error

相关问题 更多 >

    热门问题