Eugene
Eugene

Reputation: 598

Symlinks on windows

I'm trying to check is the path symlink hardlink or junction point on windows How can I do it? os.path.islink() not work. It always returns False I create symlinks by next method:

mklink /d linkPath targetDir
mklink /h linkPath targetDir    
mklink /j linkPath targetDir

I've used command line because os.link and os.symlink available only on Unix systems

Maybe there are any command line tools for it? Thanks

Upvotes: 6

Views: 1498

Answers (3)

Mayra Delgado
Mayra Delgado

Reputation: 628

Taken from https://eklausmeier.wordpress.com/2015/10/27/working-with-windows-junctions-in-python/
(see also: Having trouble implementing a readlink() function)

from ctypes import WinDLL, WinError
from ctypes.wintypes import DWORD, LPCWSTR

kernel32 = WinDLL('kernel32')

GetFileAttributesW = kernel32.GetFileAttributesW
GetFileAttributesW.restype = DWORD
GetFileAttributesW.argtypes = (LPCWSTR,) #lpFileName In

INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
FILE_ATTRIBUTE_REPARSE_POINT = 0x00400

def islink(path):
    result = GetFileAttributesW(path)
    if result == INVALID_FILE_ATTRIBUTES:
        raise WinError()
    return bool(result & FILE_ATTRIBUTE_REPARSE_POINT)

if __name__ == '__main__':
    path = "C:\\Programme" # "C:\\Program Files" on a German Windows.
    b = islink(path)
    print path, 'is link:', b

Upvotes: 0

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 59005

The os.path.islink() docstring states:

Test for symbolic link.
On WindowsNT/95 and OS/2 always returns false

In Windows the links are ending with .lnk, for files and folders, so you could create a function adding this extension and checking with os.path.isfile() and os.path.isfolder(), like:

mylink = lambda path: os.path.isfile(path + '.lnk') or  os.path.isdir(path + '.lnk')

Upvotes: 2

Rehan
Rehan

Reputation: 1339

This works on Python 3.3 on Windows 8.1 using an NTFS filesystem.

islink() returns True for a symlink (as created with mklink) and False for a normal file.

Upvotes: 1

Related Questions