Python, create a shortcut with two paths and an argument

I am trying to create a shortcut via python that will run the file in another program with an argument. For instance:

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

The code I tried fiddled 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 message:

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

I tried different line formats and google doesn't seem to know a solution to this problem.

+4
source share
2 answers
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()

Link

+3
source

Here's how to do it in Python 3.6 (the second import of @wombatonfire s solution is no longer found).

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 the site packages / comtypes / shelllink.py for more information.

0
source

Source: https://habr.com/ru/post/1649715/


All Articles