本帖最后由 fengyuwuqing 于 2025-8-19 10:01 编辑
try:
import win32com.client
except ImportError:
print("错误:缺少pywin32库,请先执行以下命令安装:")
print("pip install pywin32")
sys.exit(1)
def create_desktop_shortcut(target_path, shortcut_name):
"""在桌面创建指定文件的快捷方式
target_path:目标文件
shortcut_name:快捷方式名称
"""
try:
# 检查目标文件是否存在
if not os.path.exists(target_path):
print(f"错误:目标文件不存在 - {target_path}")
return False
# 获取桌面路径
shell = win32com.client.Dispatch("WScript.Shell")
desktop_path = shell.SpecialFolders("Desktop")
# 构建快捷方式路径
shortcut_path = os.path.join(desktop_path, f"{shortcut_name}.lnk")
# 创建快捷方式对象
shortcut = shell.CreateShortCut(shortcut_path)
shortcut.TargetPath = target_path
shortcut.WorkingDirectory = os.path.dirname(target_path) # 设置工作目录
shortcut.IconLocation = target_path # 使用程序自身图标
shortcut.Description = f"{shortcut_name} 快捷方式" # 描述信息
shortcut.save()
print(f"桌面快捷方式已创建:{shortcut_name}.lnk")
return True
except Exception as e:
print(f"创建快捷方式失败:{str(e)}")
return False
|