简体   繁体   中英

Create shortcut files in Windows 10 using Python 3.7.1

I found this piece of code, but it doesn't run anymore with Windows 10 and Python 3.7.1:

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\XXXXX\Desktop' # path to where you want to put the .lnk
path = os.path.join(desktop, 'NameOfShortcut.lnk')
target = r'C:\Users\XXXXX\Desktop\muell\picture.gif'
icon = r'C:\Users\XXXXX\Desktop\muell\icons8-link-512.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()

Is there a similar (or easier) way to create a windows shortcut?

This worked for me: (Win 10, python 2)

http://timgolden.me.uk/python/win32_how_do_i/create-a-shortcut.html

import os, sys
import pythoncom
from win32com.shell import shell, shellcon

shortcut = pythoncom.CoCreateInstance (
  shell.CLSID_ShellLink,
  None,
  pythoncom.CLSCTX_INPROC_SERVER,
  shell.IID_IShellLink
)
shortcut.SetPath (sys.executable)
shortcut.SetDescription ("Python %s" % sys.version)
shortcut.SetIconLocation (sys.executable, 0)

desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)
persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
persist_file.Save (os.path.join (desktop_path, "python.lnk"), 0)

For URLs:

import win32com.client

from os.path import join as join_paths

ALL_USERS_DESKTOP = r'C:\Users\Public\Desktop'



def create_shortcut(name, link, destination=None):
    """create_shortcut

        Create shortcut
    :param name: shortcut's name
    :type name: str
    :param link: shortcut's link
    :type link: str
    :param destination: directory where to deploy the shortcut
    :type destination: str
    :return: process result
    :rtype: bool
    """
    print('Deploying shortcut {}...'.format(name))
    if not destination:
        destination = ALL_USERS_DESKTOP

    if not name.lower().endswith('.url'):
        name = '{}.url'.format(name)

    path = join_paths(destination, name)
    print('\tDeploying shortcut at: {}.'.format(path))

    try:
        ws = win32com.client.Dispatch("wscript.shell")
        shortcut = ws.CreateShortCut(path)
        shortcut.TargetPath = link
        shortcut.Save()
    except Exception as exception:
        error = 'Failed to deploy shortcut! {}\nArgs: {}, {}, {}'.format(exception, name, link, destination)
        print(error)
        return False

    return True

A user-friendly version of code taken from https://www.codespeedy.com/create-the-shortcut-of-any-file-in-windows-using-python/

import win32com
from pathlib import Path

def make_shortcut(source, dest_dir, dest_name=None, verbose=False):
    """Make shortcut of `source` path to file in `dest_dir` target folder.
    If `dest_name` is None, will use `source`'s filename.
    """
    # process user input
    if dest_name is None:
        dest_name = Path(source).name
    dest_path = str(Path(dest_dir, dest_name)) + '.lnk'
    
    # make shortcut
    shell = win32com.client.Dispatch("WScript.Shell")
    shortcut = shell.CreateShortCut(dest_path)
    shortcut.IconLocation = source
    shortcut.Targetpath = source
    shortcut.save()
    
    # print status
    if verbose:
        print("{}\n-->\n{}".format(source, dest_path))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM