Skip to content Skip to sidebar Skip to footer

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 '

Solution 1:

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)

Solution 2:

For URLs:

import win32com.client

from os.path import join as join_paths

ALL_USERS_DESKTOP = r'C:\Users\Public\Desktop'defcreate_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))
    ifnot destination:
        destination = ALL_USERS_DESKTOP

    ifnot 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)
        returnFalsereturnTrue

Solution 3:

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

defmake_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 inputif dest_name isNone:
        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 statusif verbose:
        print("{}\n-->\n{}".format(source, dest_path))

Post a Comment for "Create Shortcut Files In Windows 10 Using Python 3.7.1"