6

I'm trying to create a shortcut through python that will launch a file in another program with an argument. E.g:

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

The code I've tried messing with:

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

But i get an error thrown my way:

AttributeError: Property '<unknown>.Targetpath' can not be set.

I've tried different formats of the string and google doesn't seem to know the solution to this problem

coco4l
  • 115
  • 5

2 Answers2

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

Reference

wombatonfire
  • 4,585
  • 28
  • 36
  • Thank you, this worked! :) But i had to do a quick and dirty `path = '"%s"' % path`, to make sure the second path had quotes around the string. The path you put in TargetPath automatically add quotes if needed (spaces in path) – coco4l Aug 01 '16 at 20:13
  • Glad to hear that it worked for you! You could accept the answer if you are happy with the solution. :) – wombatonfire Aug 01 '16 at 20:33
0

Here is how to do it on Python 3.6 (the second import of @wombatonfire s solution is not found any more).

First i did pip install comtypes, then:

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)

see site-packages/comtypes/shelllink.py for more info.

Nils Lindemann
  • 1,146
  • 1
  • 16
  • 26