如何在python中获取Windows短文件名? [英] How to get Windows short file name in python?

查看:86
本文介绍了如何在python中获取Windows短文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我的 python 代码中确定 Windows 短文件名.为此,我可以使用 win32api 找到解决方案.

I need to determine Windows short file name from my python code. For that I can find a solution using the win32api.

import win32api
long_file_name='C:\Program Files\I am a file'
short_file_name=win32api.GetShortPathName(long_file_name)

参考:http://blog.lowkster.com/2008/10/spaces-in-directory-names-i-really-love.html

不幸的是,我需要安装 pywin32ActivePython,这在我的情况下是不可能的.

Unfortunately for that I need to install pywin32 or ActivePython which is not possible in my case.

也参考了 SO:

在python中获取短路径:在python中获取短路径

Getting short path in python: Getting short path in python

推荐答案

您可以使用 ctypes.根据 MSDN 上的文档GetShortPathNameKERNEL32.DLL 中.请注意,真正的函数是用于 wide (Unicode) 字符的 GetShortPathNameW 和用于单字节字符的 GetShortPathNameA.由于宽字符更通用,我们将使用该版本.首先,根据文档设置原型:

You can use ctypes. According to the documentation on MSDN, GetShortPathName is in KERNEL32.DLL. Note that the real functions are GetShortPathNameW for wide (Unicode) characters and GetShortPathNameA for single-byte characters. Since wide characters are more general, we'll use that version. First, set the prototype according to the documentation:

import ctypes
from ctypes import wintypes
_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
_GetShortPathNameW.restype = wintypes.DWORD

GetShortPathName 在没有目标缓冲区的情况下首先调用它.它将返回制作目标缓冲区所需的字符数.然后使用该大小的缓冲区再次调用它.如果由于TOCTTOU 问题,返回值仍然较大,请继续尝试,直到您做对为止.所以:

GetShortPathName is used by first calling it without a destination buffer. It will return the number of characters you need to make the destination buffer. You then call it again with a buffer of that size. If, due to a TOCTTOU problem, the return value is still larger, keep trying until you've got it right. So:

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_unicode_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

这篇关于如何在python中获取Windows短文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆