Create shortcut files in Windows 10 using Python 3.7.1

可紊 提交于 2021-01-05 10:50:34

问题


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?


回答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)



回答2:


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


来源:https://stackoverflow.com/questions/53268792/create-shortcut-files-in-windows-10-using-python-3-7-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!