2016-07-31 99 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獲取更多信息。