os.link and os.symlink for Win32 Python

For some reason, the Win32 Python doesn’t implement hardlinks and symlinks, even though it’s there in the operating system as of Windows Vista. Here’s a simple version that’s a demonstration (a real version should memoize the lookup for the two functions, and probably handle Unicode, maybe some more error checking etc etc).

import os
import platform
import sys

source = sys.argv[1]
dest = sys.argv[2]
type = sys.argv[3]

def CreateHardLink(src, dst): 
  import ctypes
  flags = 1 if source is not None and os.path.isdir(src) else 0
  if not ctypes.windll.kernel32.CreateHardLinkA(dst, src, flags):
    raise OSError 

def CreateSymbolicLink(src, dst):
  import ctypes
  flags = 1 if source is not None and os.path.isdir(src) else 0
  if not ctypes.windll.kernel32.CreateSymbolicLinkA(dst, src, flags):
    raise OSError

if platform.system() == 'Windows':
  print 'hi there'
  os.link = CreateHardLink
  os.symlink = CreateSymbolicLink

if type == 'link':
  os.link(source, dest)
elif type == 'symlink':
  os.symlink(source, dest)
else:
  raise Exception('what?')

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>