2016-07-31 48 views
4

我想通过python创建一个快捷方式,它将在另一个带有参数的程序中启动一个文件。例如: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. 

我试过字符串的不同格式谷歌似乎并不知道这个问题的解决方案

回答

3
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() 

Reference

+0

谢谢,这工作! :)但我不得不做一个快速而脏的'path ='“%s”'%path',以确保第二个路径在字符串周围有引号。您在TargetPath中放置的路径会自动根据需要添加引号(空格在路径中) – coco4l

+0

很高兴听到它适合您!如果您对解决方案感到满意,您可以接受答案。 :) – 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) 

看到站点包/ comtypes/shelllink.py获取更多信息。