Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create shortcut files in Windows 7 using Python

Is there a simple way to create shortcuts in Windows 7 on Python? I looked it up online but they did not seem that simple.

I have tried using this simple method:

hi = open("ShortcutFile.lnk", "w")
hi.close()

Which creates a shortcut file. But how would I edit the link it is connected to. Like the file it would open? Can someone give me a push in the right direction?

like image 369
0Cool Avatar asked Nov 18 '14 04:11

0Cool


People also ask

How do you create a shortcut on Windows 7?

Click the Windows key, and then browse to the Office program for which you want to create a desktop shortcut. Right-click the program name or tile, and then select Open file location. Right-click the program name, and then click Send To > Desktop (Create shortcut). A shortcut for the program appears on your desktop.

How do you create a shortcut file?

To create a new shortcut, choose Start→All Programs and locate the program in the list of programs that appears. Right-click an item and choose Send To→Desktop (Create Shortcut). The shortcut appears on the desktop.


1 Answers

Old, but I would still like to post an answer to help out anyone who might have the same question and in need of a code example.

First, download pywin32 with pip install pywin32 or download the sourceforge binaries or the pywin32 wheel file and pip install.

import win32com.client
import pythoncom
import os
# pythoncom.CoInitialize() # remove the '#' at the beginning of the line if running in a thread.
desktop = r'C:\Users\Public\Desktop' # path to where you want to put the .lnk
path = os.path.join(desktop, 'NameOfShortcut.lnk')
target = r'C:\path\to\target\file.exe'
icon = r'C:\path\to\icon\resource.ico' # not needed, but nice

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.IconLocation = icon
shortcut.WindowStyle = 7 # 7 - Minimized, 3 - Maximized, 1 - Normal
shortcut.save()

I have used the WindowStyle when I have a GUI with a debug console, and I don't want the console to pop up all the time. I haven't tried it with a program that isn't consoled.

Hope this helps!

like image 189
Casey Avatar answered Oct 11 '22 21:10

Casey