Search code examples
pythonpython-3.6pywin32win32com

python3.6 create win32 shortcut with unicode


I have this python3.6 code that creates Windows shortcuts:

from win32com.client import Dispatch
path_to_target = r"C:\Program Files\ピチャーム\pycharm64.exe"
path_to_shortcut = r"C:\Program Files\pycharm.lnk"
shell = Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path_to_shortcut)
            
shortcut.Targetpath = path_to_target  # exception here
shortcut.save()

If path_to_target contains any non ascii characters I get an exception: Property '<unknown>.Targetpath' can not be set.

The code works OK and creates the proper shortcut if path_to_target is only ascii characters.

How can I create shortcuts to targets that have unicode characters?

Is there alternative API to create Windows shortcuts?


Solution

  • Try pythoncom instead which is Unicode compatible. Also not the target directory for the shortcut must exist before hand.

    Tested with python 3.6 64-bit

    import os
    import pythoncom
    from win32com.shell import shell
    
    shortcut_dir = r"C:\test\ピチャーム"
    if not os.path.exists(shortcut_dir):
        os.makedirs(shortcut_dir)
    
    path_to_shortcut = shortcut_dir + r"\_test.lnk"
    path_to_target = r"C:\test\target.exe"
    
    shortcut = pythoncom.CoCreateInstance(
        shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
    persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
    shortcut.SetPath(path_to_target)
    persist_file.Save (path_to_shortcut, 0)