Python, create shortcut with two paths and argument
Asked Answered
A

2

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

Anatolic answered 31/7, 2016 at 19:48 Comment(0)
F
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

Folk answered 31/7, 2016 at 21:57 Comment(2)
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)Anatolic
Glad to hear that it worked for you! You could accept the answer if you are happy with the solution. :)Folk
C
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.

Caen answered 8/5, 2017 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.