How to tell if a directory is a windows junction in python

Viewed 2632

I am running os.walk() on "C:\Users\confusedDev\Documents", I see ["My Music", "My Pictures"...] returned as subDirs but they are not actually being visited. After some research I found that they are actually junctions in Windows.

My understanding is that junction is a symlink points to directory, which gets ignored by default during os.walk(), but the following test has failed me

>>> os.path.islink("C:\\Users\\confusedDev\\Documents\\My Pictures")
False

hmm...how did os.walk() know that "C:\Users\confusedDev\Documents\My Pictures" is a symlink to "C:\Users\confusedDev\Pictures" and needed to be skipped? I want to call the same api...For now, my workaround logic simply assumes that if a directory is skipped by os.walk(), it is a junction

3 Answers

A bit late, but you can wrap os.readlink() in a try and except for directory junctions, and then put that in a function you could call, like this:

def is_junction(path: str) -> bool:
    try:
        return bool(os.readlink(path))
    except OSError:
        return False

Another way that I'm going to use is subprocess. Just calling the external windows program that gives info about links in Windows, return you a 0 as return code if link exists, and other if doesn't exists or is not a link:

fsutil reparsepoint query "<PathToTest>"

Something like this for example:

src = "C:\\Windows"
child = subprocess.Popen(
    "fsutil reparsepoint query \"{}\"".format(src),
    stdout=subprocess.PIPE
)
streamdata = child.communicate()[0]
rc = child.returncode

if rc == 0:
    print("Link exists")

On Windows 10 works fine as a normal user (also create links), but for Windows 7 you needs Admin Rights. For me is not a problem, because my application will check the link to create a new one, so it needs Admin Rights on Windows 7 anyway.

Greetings!

Related