使用Python修改Windows快捷方式

9 投票
5 回答
14647 浏览
提问于 2025-04-16 22:10

你怎么用Python来修改一个Windows快捷方式呢?

比如说,从:

H:\My Music\some_file.mp3

改成:

D:\Users\Myself\My Music\some_file.mp3

5 个回答

2

下面是如何使用Windows脚本宿主来创建快捷方式的方法:http://msdn.microsoft.com/en-us/library/fywyxt64

你可以尝试用Python把它写入文件,然后动态运行它。

4

Jonathan的解决方案非常有效。这是我根据这个方案写的一个实用函数。你只需要传入快捷方式文件的名字(比如“Mozilla Firefox.lnk”,不需要写完整的文件路径),还有新的快捷方式目标,它就会被修改。

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

def short_target(filename,dest):
    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, filename)
    persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
    persist_file.Load (shortcut_path)
    shortcut.SetPath(dest)
    mydocs_path = shell.SHGetFolderPath (0, shellcon.CSIDL_PERSONAL, 0, 0)
    shortcut.SetWorkingDirectory (mydocs_path)
    persist_file.Save (shortcut_path, 0)

唯一的依赖是pywin32这个库。另外要注意,你可以在快捷方式目标中指定一些选项和参数。要使用这个功能,只需调用:

short_target("shortcut test.lnk",'C:\\')   #note that the file path must use double backslashes rather than single ones. This is because backslashes are used for special characters in python (\n=enter, etc) so a string must contain two backslashes for it to be registered as one backslash character.

这个例子会把你桌面上名为“shortcut test”的快捷方式的目标设置为打开硬盘根目录(C:)的文件管理器的快捷方式。

8

这里有另一种更合适的方法,可以使用Python的Winshell库来实现这个功能:使用Python创建Windows快捷方式。在你的情况下,代码大概会是这样的:

import os, winshell
from win32com.client import Dispatch

desktop = winshell.desktop()
path = os.path.join(desktop, "some_file.mp3.lnk")
target = r"D:\Users\Myself\My Music\some_file.mp3"
wDir = r"D:\Users\Myself\My Music"
icon = r"D:\Users\Myself\My Music\some_file.mp3"

shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()

如果已经有的快捷方式需要被删除或者重写。如果你需要批量处理快捷方式文件,我觉得有办法可以读取现有快捷方式的路径,但我没找到具体的方法。

撰写回答