您可以使用
ctypes。根据MSDN上的文档,
GetShortPathName位于中
KERNEL32.DLL。需要注意的是真正的功能是
GetShortPathNameW用于
W¯¯
IDE(Unipre)字符和
GetShortPathNameA单字节字符。由于宽字符更为通用,因此我们将使用该版本。首先,根据文档设置原型:
import ctypesfrom ctypes import wintypes_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]_GetShortPathNameW.restype = wintypes.DWORD
GetShortPathName通过在没有目标缓冲区的情况下首先调用它来使用。它将返回创建目标缓冲区所需的字符数。然后,使用该大小的缓冲区再次调用它。如果由于TOCTTOU问题,返回值仍然较大,请继续尝试直到正确为止。所以:
def get_short_path_name(long_name): """ Gets the short path name of a given long path. http://stackoverflow.com/a/23598461/200291 """ output_buf_size = 0 while True: output_buf = ctypes.create_unipre_buffer(output_buf_size) needed = _GetShortPathNameW(long_name, output_buf, output_buf_size) if output_buf_size >= needed: return output_buf.value else: output_buf_size = needed



