【发布时间】:2015-12-09 09:30:45
【问题描述】:
我想更改 python 处理返回的错误字符串的语言的方式,例如 WinError/OSError 异常。我正在使用 ctypes 并且 WinError 被定义为
def WinError(code=None, descr=None):
if code is None:
code = GetLastError()
if descr is None:
descr = FormatError(code).strip()
return OSError(None, descr, None, code)
FormatError函数是从..\Python34\DLLs_ctypes.pyd中提取出来的,是C++ FormatMessage函数的python版本。
DWORD WINAPI FormatMessage(
_In_ DWORD dwFlags,
_In_opt_ LPCVOID lpSource,
_In_ DWORD dwMessageId,
_In_ DWORD dwLanguageId,
_Out_ LPTSTR lpBuffer,
_In_ DWORD nSize,
_In_opt_ va_list *Arguments
);
理想情况下,python 等效项应该具有相同的参数,但 FormatError 只能有一个参数,即 FormatError([code])。 我找到了用 c++ 编写的 ctypes 的源代码。有一个名为 callproc.c 的文件,其中定义了 FormatError 函数
static TCHAR *FormatError(DWORD code)
{
TCHAR *lpMsgBuf;
DWORD n;
n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL);
if (n) {
while (isspace(lpMsgBuf[n-1]))
--n;
lpMsgBuf[n] = '\0'; /* rstrip() */
}
return lpMsgBuf;
}
LANG_NEUTRAL|SUBLANG_DEFAULT = 回退到用户的默认语言。
有没有办法控制错误字符串的语言,可能是通过设置语言环境、环境变量或其他方式?
提前致谢!
编辑:我想我发现了一些有趣的东西,但我稍后会测试它,因为我真的很困。这应该有效吗? https://gist.github.com/EBNull/6135237
【问题讨论】:
-
stackoverflow.com/questions/28180159/… 给出了一个自定义格式化程序的示例,它继承了 logging.Formatter 并覆盖了它的格式。
标签: python c++ exception ctypes