os.path.expanduser("~") 的替代方法? [英] An alternative to os.path.expanduser("~")?

查看:52
本文介绍了os.path.expanduser("~") 的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 2.7.x 中,os.path.expanduser("~") 对于 Unicode 已损坏.

In python 2.7.x, os.path.expanduser("~") is broken for Unicode.

这意味着如果~"的扩展中包含非 ascii 字符,则会出现异常.

This means that you get an exception if the expansion of "~" has non-ascii characters in it.

http://bugs.python.org/issue13207

我怎样才能以其他方式实现相同的目标?

How can I achieve the same, some other way?

(也就是说,如何获取到用户主目录"的路径,在Win7上通常是C:\Users\usern-name)?

(That is to say, how can I get the path to the user's "home directory", which would usually be C:\Users\usern-name on Win7)?

推荐答案

您链接到的错误报告包括一个 解决方法脚本,它直接从 Win32 API 检索相关的主目录信息:

The bug report you link to includes a workaround script, which retrieves the relevant home directory information directly from the Win32 API:

import ctypes
from ctypes import windll, wintypes

class GUID(ctypes.Structure):
    _fields_ = [
         ('Data1', wintypes.DWORD),
         ('Data2', wintypes.WORD),
         ('Data3', wintypes.WORD),
         ('Data4', wintypes.BYTE * 8)
    ]

    def __init__(self, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8):
        """Create a new GUID."""
        self.Data1 = l
        self.Data2 = w1
        self.Data3 = w2
        self.Data4[:] = (b1, b2, b3, b4, b5, b6, b7, b8)

    def __repr__(self):
        b1, b2, b3, b4, b5, b6, b7, b8 = self.Data4
        return 'GUID(%x-%x-%x-%x%x%x%x%x%x%x%x)' % (
                   self.Data1, self.Data2, self.Data3, b1, b2, b3, b4, b5, b6, b7, b8)

# constants to be used according to the version on shell32
CSIDL_PROFILE = 40
FOLDERID_Profile = GUID(0x5E6C858F, 0x0E22, 0x4760, 0x9A, 0xFE, 0xEA, 0x33, 0x17, 0xB6, 0x71, 0x73)

def expand_user():
    # get the function that we can find from Vista up, not the one in XP
    get_folder_path = getattr(windll.shell32, 'SHGetKnownFolderPath', None)
    if get_folder_path is not None:
        # ok, we can use the new function which is recomended by the msdn
        ptr = ctypes.c_wchar_p()
        get_folder_path(ctypes.byref(FOLDERID_Profile), 0, 0, ctypes.byref(ptr))
        return ptr.value
    else:
        # use the deprecated one found in XP and on for compatibility reasons
       get_folder_path = getattr(windll.shell32, 'SHGetSpecialFolderPathW', None)
       buf = ctypes.create_unicode_buffer(300)
       get_folder_path(None, buf, CSIDL_PROFILE, False)
       return buf.value

这个 expand_user() 函数只返回当前用户的主目录.

This expand_user() function returns the home directory for the current user only.

这篇关于os.path.expanduser("~") 的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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