使用Python在Windows 7中创建快捷方式文件

0Co*_*ool 7 python operating-system shortcut windows-7

有没有一种简单的方法可以在Windows 7上的Python中创建快捷方式?我在网上查询了一下,但看起来似乎并不简单。

我尝试使用这种简单的方法:

hi = open("ShortcutFile.lnk", "w")
hi.close()
Run Code Online (Sandbox Code Playgroud)

这将创建一个快捷方式文件。但是我将如何编辑它连接的链接。像打开文件一样?有人可以向我推正确的方向吗?

Cas*_*sey 7

旧的,但是我仍然想发布答案,以帮助那些可能有相同问题并且需要代码示例的人。

首先,使用下载pywin32 pip install pywin32或下载sourceforge二进制文件或pywin32 wheel文件和pip install

import win32com.client
import pythoncom
import os
# pythoncom.CoInitialize() # remove the '#' at the beginning of the line if running in a thread.
desktop = r'C:\Users\Public\Desktop' # path to where you want to put the .lnk
path = os.path.join(desktop, 'NameOfShortcut.lnk')
target = r'C:\path\to\target\file.exe'
icon = r'C:\path\to\icon\resource.ico' # not needed, but nice

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.IconLocation = icon
shortcut.WindowStyle = 7 # 7 - Minimized, 3 - Maximized, 1 - Normal
shortcut.save()
Run Code Online (Sandbox Code Playgroud)

我用过 WindowStyle,当我有一个调试控制台的GUI,我不希望控制台弹出所有的时间。我没有用没有控制台的程序尝试过。

希望这可以帮助!

  • 我收到一条错误消息“发生异常:com_error (-2147352567, '发生异常。', (0, 'WshShortcut.Save', '无法保存快捷方式 "C:\\Users\\Public\\Desktop\\NameOfShortcut .lnk“.',无,0,-2147024891),无)”快捷方式.save()。 (2认同)

Kou*_*und 5

如果您正在寻找与 Python 3 一起使用的独立于平台的版本,请查看swinlnk

from swinlnk.swinlnk import SWinLnk
swl = SWinLnk()
swl.create_lnk('W:\Foo\Bar', '/mnt/win_share/playground/Bar_winlink.lnk')
Run Code Online (Sandbox Code Playgroud)

该 python 脚本基于 C/Bash 工具mslink


小智 0

您当前正在执行的操作是在计算机上的当前工作目录中创建相当于空文件(在本例中为快捷方式)的文件。

要使该文件成为可用的快捷方式,您需要向正在创建的文件写入一些信息,告诉 Windows 该快捷方式文件将要执行的操作。在这种情况下,这将是您希望它运行的快捷方式类型以及完成手头任务所需的任何其他参数。

我相信 pywin32 对于大多数任务都会派上用场:http ://sourceforge.net/projects/pywin32/

如果您要创建 Internet 快捷方式,可以在此页面上找到示例(使用 pywin32):http://www.blog.pythonlibrary.org/2010/01/23/using-python-to-create-shortcuts /

如果您想要创建 Internet 快捷方式以外的其他内容,则需要查找适合您要运行的快捷方式类型的 Windows 命令(例如,打开特定应用程序或特定文件)。