Symlinks on windows
Asked Answered
C

3

6

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

Clare answered 18/6, 2013 at 16:59 Comment(0)
D
2

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')
Deft answered 18/6, 2013 at 17:0 Comment(5)
I think it not correct. At least because I need in a link to folder also. Also extension does not guarantee what path is symlink or notClare
Thank you but it does not guarantee me that path is symlink. I would like to check all paths.Clare
How this answer got 3 upvotes is beyond me. The extension has absolutely zip to do with whether something is considered a link or not. Also, .lnk files are merely a left-over from the "good" old days of Windows 98, when Windows didn't support anything remotely resembling symbolic links like UNIX / Linux had for ages.Goodsized
@Goodsized I understand your critic... unfortunately I could not come up with a better answer. Do you have something better in mind? Why do you think this answer does not address the OP's question?Deft
@SaulloCastro: because shortcuts are NOT symbolic links!Tipperary
B
1

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.

Burgonet answered 11/12, 2013 at 5:55 Comment(0)
T
0

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
Tipperary answered 11/4, 2019 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.