Skip to main content
 首页 » 编程设计

python之如何在 Windows 上创建文件夹的快捷方式

2025年02月15日8jirigala

我已经为可执行文件创建了快捷方式并且它有效,但是当我尝试为文件夹创建快捷方式时它不起作用。 它确实创建了一个快捷方式,只是不是正确的“目标类型”。请看下面的图片。 目标类型应该是“文件夹”,而不是"file"。问题是,当我打开快捷方式时,它会询问我要用哪个程序打开文件,但它不会打开文件夹。

我用来创建快捷方式的函数如下

from win32com.client import Dispatch 
import winshell 
import os 
 
def create_shortcuts(self, tool_name, exe_path, startin, icon_path): 
 
    shell = Dispatch('WScript.Shell') 
    shortcut_file = os.path.join(winshell.desktop(), tool_name + '.lnk') 
    shortcut = shell.CreateShortCut(shortcut_file) 
    shortcut.Targetpath = exe_path 
    shortcut.WorkingDirectory = startin 
    shortcut.IconLocation = icon_path 
    shortcut.save() 

我不知道是否可以设置“目标类型”。我找不到办法做到这一点,但我知道一定有办法。

请您参考如下方法:

如果您想使用 .Net“clr”(特别是如果您已经需要它):

首先运行此...您必须将此命令的输出与您的应用程序一起发送:

"c:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\TlbImp.exe" %SystemRoot%\system32\wshom.ocx /out:Interop.IWshRuntimeLibrary.dll 

如果您以相当标准的方式安装 Windows SDK,tlbimp.exe 甚至可能在路径中。但如果没有,也没关系,您只需将“程序集”(在 .Net 领域中提供接口(interface)的 dll 的奇特词)与您的应用程序一起发布。

然后这段代码将在 python 中运行:

import clr 
sys.path.append(DIRECTORY_WHERE_YOU_PUT_THE_DLL) 
clr.AddReference('Interop.IWshRuntimeLibrary') 
import Interop.IWshRuntimeLibrary 
sc = Interop.IWshRuntimeLibrary.WshShell().CreateShortcut("c:\\test\\sc.lnk") 
isc = Interop.IWshRuntimeLibrary.IWshShortcut(sc) 
isc.set_TargetPath("C:\\") 
isc.Save() 

....上面的代码,有太多的修改和序言,甚至可能适用于 Mono。