Python,创建带有两个路径和参数的快捷方式。

6

我正在尝试通过Python创建一个快捷方式,以便使用参数在另一个程序中启动文件。例如:

"C:\file.exe" "C:\folder\file.ext" argument

我尝试过的代码如下:
from win32com.client import Dispatch
import os

shell = Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)

shortcut.Targetpath = r'"C:\file.exe" "C:\folder\file.ext"'
shortcut.Arguments = argument
shortcut.WorkingDirectory = "C:\" #or "C:\folder\file.ext" in this case?
shortcut.save()

但是我遇到了一个错误:
AttributeError: Property '<unknown>.Targetpath' can not be set.

我尝试了不同的字符串格式,但谷歌似乎并不知道如何解决这个问题。

2个回答

5
from comtypes.client import CreateObject
from comtypes.gen import IWshRuntimeLibrary

shell = CreateObject("WScript.Shell")
shortcut = shell.CreateShortCut(path).QueryInterface(IWshRuntimeLibrary.IWshShortcut)

shortcut.TargetPath = "C:\file.exe"
args = ["C:\folder\file.ext", argument]
shortcut.Arguments = " ".join(args)
shortcut.Save()

参考文献


谢谢,这个方法好用! :) 不过我得做一个快速而简单的 path = '"%s"' % path,以确保第二个路径字符串周围有引号。您放在TargetPath中的路径如果需要(路径中有空格)就会自动添加引号。 - coco4l
很高兴听到它对你有用!如果你对解决方案感到满意,可以接受这个答案。 :) - wombatonfire

0

以下是在Python 3.6上的操作方法(@wombatonfire的解决方案中第二个导入不再被找到)。

首先我执行了pip install comtypes,然后:

import comtypes
from comtypes.client import CreateObject
from comtypes.persist import IPersistFile
from comtypes.shelllink import ShellLink

# Create a link
s = CreateObject(ShellLink)
s.SetPath('C:\\myfile.txt')
# s.SetArguments('arg1 arg2 arg3')
# s.SetWorkingDirectory('C:\\')
# s.SetIconLocation('path\\to\\.exe\\or\\.ico\\file', 1)
# s.SetDescription('bla bla bla')
# s.Hotkey=1601
# s.ShowCMD=1
p = s.QueryInterface(IPersistFile)
p.Save("C:\\link to myfile.lnk", True)

# Read information from a link
s = CreateObject(ShellLink)
p = s.QueryInterface(IPersistFile)
p.Load("C:\\link to myfile.lnk", True)
print(s.GetPath())
# print(s.GetArguments())
# print(s.GetWorkingDirectory())
# print(s.GetIconLocation())
# print(s.GetDescription())
# print(s.Hotkey)
# print(s.ShowCmd)

请参阅 site-packages/comtypes/shelllink.py 以获取更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接