views:

622

answers:

2

Is there a way to create an NTFS junction point in Python? I know I can call the junction utility, but it would be better not to rely on external tools.

+1  A: 

You don't want to rely on external tools but you don't mind relying on the specific environment? I think you could safely assume that, if it's NTFS you're running on, the junction utility will probably be there.

But, if you mean you'd rather not call out to an external program, I've found the ctypes stuff to be invaluable. It allows you to call Windows DLLs directly from Python. And I'm pretty sure it's in the standard Python releases nowadays.

You'd just have to figure out which Windows DLL the CreateJunction() (or whatever Windows calls it) API call is in and set up the parameters and call. Best of luck with that, Microsoft don't seem to support it very well. You could disassemble the SysInternals junction program or linkd or one of the other tools to find out how they do it.

Me, I'm pretty lazy, I'd just call junction as an external process :-)

paxdiablo
ctypes is included in Python from 2.5 onwards.
Torsten Marek
The junction command doesn't exist on Vista and Win7. It's been replaced by mklink.
Therms
+6  A: 

you can use python win32 API modules e.g.

import win32file

win32file.CreateSymbolicLink(fileSrc, fileTarget, 1)

see http://docs.activestate.com/activepython/2.5/pywin32/win32file__CreateSymbolicLink_meth.html for more details

if you do not want to rely on that too, you can always use ctypes and directly call CreateSymbolicLinl win32 API, which is anyway a simple call

here is example call using ctypes

import ctypes

kdll = ctypes.windll.LoadLibrary("kernel32.dll")

kdll.CreateSymbolicLinkA("d:\test.txt", "d:\test_link.txt", 0)

MSDN (http://msdn.microsoft.com/en-us/library/aa363866(VS.85).aspx) says Minimum supported client Windows Vista

Anurag Uniyal
I think junctions were from Win2K onwards but not officially (or well) supported by MS, given the scarcity of docs on how to do it. The new symbolic links look a lot better, especially since you can do them to files and (I think) they can now cross networks.
paxdiablo
yes junctions are subset of symbolic links
Anurag Uniyal
Junctions are _not_ a subset of symbolic links. Junctions only apply to directories. This answer is incorrect and creates a symbolic link for files (which only works on Vista and above) rather than a junction for directories (which works on NTFS in Windows 2000) and above. Unfortunately, there's no real easy way of doing this in Python.
Mike McQuaid