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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Why am I getting UnauthorizedAccessException on th
- Evil ctypes hack in python
Since Python 3.5 there's a function
CreateJunction
in_winapi
module.you can use python win32 API modules e.g.
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
MSDN says Minimum supported client Windows Vista
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 SysInternalsjunction
program orlinkd
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 :-)I answered this in a similar question, so I'll copy my answer to that below. Since writing that answer, I ended up writing a python-only (if you can call a module that uses ctypes python-only) module to creating, reading, and checking junctions which can be found in this folder. Hope that helps.
Also, unlike the answer that utilizes uses the CreateSymbolicLinkA API, the linked implementation should work on any Windows version that supports junctions. CreateSymbolicLinkA is only supported in Vista+.
Answer:
python ntfslink extension
Or if you want to use pywin32, you can use the previously stated method, and to read, use:
Adjust the attributes in the CreateFile to your needs, but for a normal situation, it should work. Feel free to improve on it.
It should also work for folder junctions if you use MOUNTPOINT instead of SYMBOLIC_LINK.
You may way to check that
if you put this into something you're releasing, since this form of symbolic link is only supported on Vista+.
Based on the accepted answer by Charles, here improved (and cross-platform) versions of the functions (Python 2.7 and 3.5+).