windll获取错误消息

windll获取错误消息

本文介绍了从ctypes windll获取错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python脚本更改Windows 7计算机上的墙纸。

I'm trying to use a Python script to change the wallpaper on a windows 7 computer. If it matters, I'm invoking the script from a node-webkit application.

缩短的脚本如下所示:

# ...
result = ctypes.windll.user32.SystemParametersInfoA(20, 0, path, 0)

通常,它可以工作,但是有时,似乎是随机的,它却不能。除了状态码(0或1),我有什么办法可以获取有关该错误的更多信息?

Often, it works, but sometimes, seemingly randomly, it does not. Is there any way for me to retrieve more info about the error than the status code (0 or 1)?

我一直在尝试使用GetLastError,有时会提到相对于ctypes库,但无法提取任何错误信息。

I've been trying to use GetLastError which is sometimes mentioned in relation to the ctypes library, but have been unable to extract any error information.

推荐答案

ctypes文档建议使用 use_last_error = True 可以安全地捕获 GetLastError()。请注意,在引发 WinError 时需要检索错误代码:

The ctypes documentation recommends using use_last_error=True to capture GetLastError() in a safe way. Note you need to retrieve the error code when raising WinError:

from ctypes import *

SPI_SETDESKWALLPAPER = 0x0014
SPIF_SENDCHANGE = 2
SPIF_UPDATEINIFILE = 1

def errcheck(result, func, args):
    if not result:
        raise WinError(get_last_error())

user32 = WinDLL('user32',use_last_error=True)
SystemParametersInfo = user32.SystemParametersInfoW
SystemParametersInfo.argtypes = [c_uint,c_uint,c_void_p,c_uint]
SystemParametersInfo.restype = c_int
SystemParametersInfo.errcheck = errcheck

SystemParametersInfo(SPI_SETDESKWALLPAPER,0,r'xxx',SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)

输出:

Traceback (most recent call last):
  File "C:\test.py", line 17, in <module>
    SystemParametersInfo(SPI_SETDESKWALLPAPER,0,r'c:\xxx',SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)
  File "C:\test.py", line 9, in errcheck
    raise WinError(get_last_error())
FileNotFoundError: [WinError 2] The system cannot find the file specified.

所有这些工作的替代方法是使用并调用 win32gui.SystemsParametersInfo

An alternative to all this work is to use pywin32 and call win32gui.SystemsParametersInfo.

这篇关于从ctypes windll获取错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 07:29