Skip to main content

在 Windows 下使用 Python 生成软链接、硬链接

技术
Author

cookwhy

Published

May 23, 2013

Windows 有一个 CreateSymbolicLink 函数,可以用来创建软硬链接,不过对操作系统有硬性要求,桌面版本需要 Windows Vista 以上,服务器版本需要 Windows Server 2008 版本以上。

如果是在 Python 程序需要使用软链接或是硬链接来做一些文件操作,可以有两种方法:

  1. 直接使用 Python Win32 API 模块:

<pre class="src src-python"><span style="color: #8ac6f2;font-weight: bold">import</span> win32file
win32file.CreateSymbolicLink(fileSrc, fileTarget, 1)

  1. 使用 ctypes 来实现 os.symlink 这个功能的抽象,以方便跨平台:

<pre class="src src-python"><span style="color: #8ac6f2;font-weight: bold">import</span> os

from ctypes import *

__CSL = None def symlink(source, link_name): ’’’symlink(source, link_name) Creates a symbolic link pointing to source named link_name’’’ global __CSL if __CSL is None: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte __CSL = csl flags = 0 if source is not None and os.path.isdir(source): flags = 1 if __CSL(link_name, source, flags) == 0: #raise ctypes.WinError() print “raise ctypes.WinError() Error”

os.symlink = symlink
<p>
  定义了上述函数后,就可以直接在代码里用下面的函数来创建软、硬链接了:
</p>

<pre class="src src-python"><span style="color: #8ac6f2;font-weight: bold">if</span> <span style="color: #8ac6f2;font-weight: bold">not</span> os.path.islink(docpath):
os.symlink(path, docpath)

  1. 使用第三方右键菜单扩展工具:Link Shell Extension

<p>
  如果是在 Windows XP 或是更低版本的操作系统里,是没有办法用上述两种办法,不过可以用 <a href="http://schinagl.priv.at/nt/hardlinkshellext/hardlinkshellext.html">Link Shell Extension</a> 来手动创建一个软、硬链接。
</p>

<p>
  如果是在 Windows Vista 或是 Windows 7 上,可以使用 mklink 这个命令来创建链接。
</p>