Symlinks on windows?

Viewed 39928

Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.

10 Answers

Trying to create a Symlink in Windows I always got the error

A required privilege is not held by the client

However I was successfull when creating a shortcut with this code

import win32com.client
import pythoncom
import os

def create_shortcut(original_filepath, shortcut_filepath):
    shell = win32com.client.Dispatch("WScript.Shell")
    shortcut = shell.CreateShortCut(shortcut_filepath)
    shortcut.Targetpath = original_filepath
    shortcut.WindowStyle = 7
    shortcut.save()

create_shortcut(r'C:\Users\xxx\Desktop\test.jpg', 
                r'C:\Users\xxx\Desktop\test.lnk')

Note: make sure the shortcut ends with '.lnk'

As mentioned in another answer, using subprocess.call is likely the best option for windows. However calling 'mklink' directly may result in:

[WinError 2] The system cannot find the file specified

On Windows Server 2016, I was able to get the following to work for files:

import subprocess
subprocess.call(['cmd', '/c', 'mklink', '<path_for_symlink>', '<path_for_file>'])

Change the switches above as per mklink docs.

Related