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

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Eugene
  • 588
  • 1
  • 8
  • 20

3 Answers3

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')
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
  • 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 not – Eugene Jun 18 '13 at 17:59
  • Thank you but it does not guarantee me that path is symlink. I would like to check all paths. – Eugene Jun 18 '13 at 18:19
  • 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. – antred Apr 15 '16 at 19:50
  • @antred 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? – Saullo G. P. Castro Apr 16 '16 at 14:26
  • 1
    @SaulloCastro: because shortcuts are NOT symbolic links! – Mayra Delgado Dec 09 '16 at 11:07
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.

Rehan
  • 1,299
  • 2
  • 16
  • 19
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
Mayra Delgado
  • 531
  • 4
  • 17