Python and Windows Symbolic Links

Python, like many other popular OSS (Git anyone?), does not support symbolic links on Windows platforms , although they have been around since Windows Vista. Note, I am referring to actual symbolic links, not NTFS directory junctions or shortcuts.

I’m not really sure why is that. Maybe because they do not distinguish between different Windows revisions?

My current approach is to use the OS commands to create/delete symlinks. It’s not very elegant but it works without compatibility issues, unlike other solutions (calling win32 api through DLLs, manipulating file attributes, and other stuff you find in StackOverflow or tech blogs)

For example, to create a symbolic link of directories, one can use:

 child = subprocess.Popen(['MKLINK', '/D', link, target], stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True)
 streamdata = child.communicate()[0]

And check child.returncode for the result (and the output – stdout and stderr combined – available in the streamdata variable)

To remove a symbolic link to a directory, use the windows RMDIR command (os.rmdir or os.unlink won’t work)

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s