正如Mike所说,您可以从获得系统代码页
getfilesystemencoding。此编码用于将Windows的本机Unipre字符串转换为Python使用的所有C
stdio函数的字节,包括使用字节字符串filepath和的文件系统调用
os.environ。
这意味着您将能够从中读取具有非ASCII字符的字符串,
os.environ并将其直接用作文件路径,而无需任何特殊的编码/解码步骤。
不幸的是,如果
%APPDATA%变量包含系统代码页中不存在的Unipre字符-
例如,如果在德语(cp1252)Windows安装中,您的路径是
C:documents and SettingsαβγApplicationData
-那么在获得使用这些字符之前,这些字符将已经被修饰。。在这种情况下,使用filesystemencoding将获得的字节字符串解码为Unipre将无济于事。
您可以在具有
ctypes扩展名的最新Python版本上使用此函数来读取Windows本机Unipre环境变量。
def getEnvironmentVariable(name): name= unipre(name) # make sure string argument is unipre n= ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0) if n==0: return None buf= ctypes.create_unipre_buffer(u' '*n) ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n) return buf.value
在Python 3中,该
os.environ词典包含直接从Windows获取的Unipre字符串,而没有代码页编码,因此您不必担心那里的这个问题。



