如何在python中使用SHGetFileInfo with SHGFI_PIDL



我正在尝试使用SHGetFileInfo检索文件信息(特别是有关图标的信息(。实际上,我没有文件的完整路径,我只有pidl。

下面的代码返回(0L, (0, 0, 0, '', '')),我的问题是为什么。

from win32com.shell import shell, shellcon
def get_info():
    desktop = shell.SHGetDesktopFolder()
    eaten, desktop_pidl, attr = desktop.ParseDisplayName(None, None, r"C:UsersEllaDesktop")
    return shell.SHGetFileInfo(desktop_pidl, 0, shellcon.SHGFI_PIDL | shellcon.SHGFI_SYSICONINDEX | shellcon.SHGFI_ICON | shellcon.SHGFI_DISPLAYNAME)

另一方面,由于某种原因,下面的代码确实有效(它使用完整路径而不是 pidl(:

from win32com.shell import shell, shellcon
def get_info2():
    return shell.SHGetFileInfo(r"C:UsersEllaDesktop", 0, shellcon.SHGFI_SYSICONINDEX | shellcon.SHGFI_ICON | shellcon.SHGFI_DISPLAYNAME)

谢谢!

您在 PySHGetFileInfo 中发现了一个错误。如果SHGFI_PIDL设置在标志中,它会调用PyObject_AsPIDL并将结果存储到pidl_or_name,但它错误地将name传递给SHGetFileInfo,在这种情况下是初始NULL值。有关更多详细信息,请参阅下文。

您询问如何在shell32!SHGetFileInfoW上设置断点。对此没有简单的答案。相反,请允许我分享一下我为测试这个所做的概述。希望这至少能让你开始。

测试环境:

  • 64 位视窗 7 SP1 (6.1.7601(
  • Windows SDK 7.1(确保已安装调试器(
  • Visual Studio 2010 SP1
  • Visual C++ 2010 SP1 编译器更新
  • Python 3.4(和调试文件(
  • 汞(hg.exe,不是汞(

设置外壳环境。

"C:Program FilesMicrosoft SDKsWindowsv7.1BinSetEnv.Cmd"
set MSSdk=%WindowsSDKDir%
set SYMDIR=C:Symbols
set SYMSRV=http://msdl.microsoft.com/download/symbols    
set _NT_SYMBOL_PATH=symsrv*symsrv.dll*%SYMDIR%*%SYMSRV%
path C:Program FilesDebugging Tools for Windows (x64);%PATH%
path C:Program FilesMercurial;%PATH%

创建 Python 虚拟环境。

py -3.4 -m venv --symlinks test

venv 不会链接.pdb文件,因此请在 for 循环中手动获取这些文件。

set PYDIR="%ProgramW6432%Python34"
set CMD=mklink "testScripts%~nxf" "%f"
for /R %PYDIR% %f in (*.pdb) do @%CMD%

激活虚拟环境。

testScriptsactivate

克隆 PyWin32 存储库。生成并安装版本 219。

set HGSRV=http://pywin32.hg.sourceforge.net
hg clone %HGSRV%/hgroot/pywin32/pywin32
cd pywin32
hg up b219

我编辑了 setup.py 以注释掉与建筑相关的所有内容 win32com.mapi .我的设置甚至没有所需的标头, 当我获得它们时,构建 WIN64 的扩展。

生成并安装包。

python setup3.py install

在控制台调试器 cdb.exe 下运行 Python。

>cdb -xi ld python
Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.
CommandLine: python
Symbol search path is: symsrv*symsrv.dll*C:Symbols*
                       http://msdl.microsoft.com/download/symbols
Executable search path is:
(d50.1174): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00000000`770bcb70 cc              int     3
0:000> bp shell32!SHGetFileInfoW
0:000> g
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:16:31)
[MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

上述命令行中-xi ld的选项设置了一个过滤器以忽略打印加载的模块。网上有很多教程和"备忘单",用于使用 Microsoft 的调试器,如 WinDbg、cdb 和 kd。调试器都使用相同的引擎,因此它们支持一组通用的调试命令。

附加的调试器在 shell32!SHGetFileInfoW 上设置了断点。触发断点时,调试器将获取控制台。Windows 控制台为数不多的可兑换功能之一是其每个应用程序的输入历史记录和别名。这样可以方便地在同一控制台窗口中弹入和跳出调试器和调试对象时调用命令。

>>> import os
>>> from win32com.shell import shell, shellcon
>>> print(shell.__file__)
C:Temptestlibsite-packageswin32comextshellshell.pyd
>>> path = os.path.expanduser(r'~Desktopdesktop.ini')
>>> pidl = shell.SHParseDisplayName(path, 0, None)[0]
>>> flags = (shellcon.SHGFI_PIDL |
...          shellcon.SHGFI_SYSICONINDEX |
...          shellcon.SHGFI_ICON |
...          shellcon.SHGFI_DISPLAYNAME)
>>> shell.SHGetFileInfo(pidl, 0, flags)
Breakpoint 0 hit
SHELL32!SHGetFileInfoW:
000007fe`fd692290 fff3            push    rbx
0:000> k 5
*** WARNING: Unable to verify checksum for
C:Temptestlibsite-packageswin32comextshellshell.pyd
Child-SP          RetAddr           Call Site
00000000`003ff2d8 00000000`5f44c5e8 SHELL32!SHGetFileInfoW
00000000`003ff2e0 00000000`5f5af8bd shell!PySHGetFileInfo+0xf8
00000000`003ff610 00000000`5f62385b python34!PyCFunction_Call+0x12d
00000000`003ff640 00000000`5f625c89 python34!call_function+0x2ab
00000000`003ff6a0 00000000`5f62770c python34!PyEval_EvalFrameEx+0x2279
0:000> r rcx
rcx=0000000000000000
0:000> g
(0, (0, 0, 0, '', ''))

在 Windows x64 ABI 中,函数的第一个参数在寄存器rcx中传递。我们从SHGetFileInfo文档中知道这应该是PIDL,但实际上NULL正在通过。显然这是一个错误。堆栈跟踪将责任归咎于shell!PySHGetFileInfo。以下是有问题的代码片段:

    if (flags & SHGFI_PIDL) {
        ok = PyObject_AsPIDL(obName, &pidl, FALSE);
        pidl_or_name = (TCHAR *)pidl;
    } else {
        ok = PyWinObject_AsTCHAR(obName, &name, FALSE);
        pidl_or_name = name;
    }
    if (!ok)
        return NULL;
    SHFILEINFO info;
    memset(&info, 0, sizeof(info));
    info.dwAttributes = info_attrs;
    PY_INTERFACE_PRECALL;
    DWORD_PTR dw = SHGetFileInfo(name, attr, &info, sizeof(info), flags);

错误是将name作为第一个参数传递而不是pidl_or_name


该问题被标记为 ctypes。IMO,如果这样做消除了诸如 PyWin32 之类的大型依赖项,那么使用 ctypes 是值得的。对于基于 COM 的 API,我通常不会单独使用 ctypes。如果你想尝试的话,comtypes 包建立在 ctypes 上。在这种情况下,可以通过调用 SHParseDisplayName 来避免直接调用 COM 方法。除了使用HRESULT返回代码之外,它几乎与任何其他 Win32 API 非常相似。

import types as _types
import ctypes as _ctypes
from ctypes import wintypes as _wtypes
_mtypes = _types.ModuleType('_mtypes')
_ole32 = _ctypes.WinDLL('ole32')
_shell32 = _ctypes.WinDLL('shell32')
_user32 = _ctypes.WinDLL('user32')
try:
    from win32com.shell import shell as _shell
except ImportError:
    _shell = None
try:
    from win32com.shell import shellcon
except ImportError:
    shellcon = _types.ModuleType('shellcon')
    shellcon.SHGFI_LARGEICON         = 0x00000
    shellcon.SHGFI_SMALLICON         = 0x00001
    shellcon.SHGFI_OPENICON          = 0x00002
    shellcon.SHGFI_SHELLICONSIZE     = 0x00004
    shellcon.SHGFI_PIDL              = 0x00008
    shellcon.SHGFI_USEFILEATTRIBUTES = 0x00010
    shellcon.SHGFI_ICON              = 0x00100
    shellcon.SHGFI_DISPLAYNAME       = 0x00200
    shellcon.SHGFI_TYPENAME          = 0x00400
    shellcon.SHGFI_ATTRIBUTES        = 0x00800
    shellcon.SHGFI_ICONLOCATION      = 0x01000
    shellcon.SHGFI_EXETYPE           = 0x02000
    shellcon.SHGFI_SYSICONINDEX      = 0x04000
    shellcon.SHGFI_LINKOVERLAY       = 0x08000
    shellcon.SHGFI_SELECTED          = 0x10000
    shellcon.SHGFI_ATTR_SPECIFIED    = 0x20000
try:
    import win32con
except ImportError:
    win32con = _types.ModuleType('win32con')
    win32con.MAX_PATH = 260
    win32con.FILE_ATTRIBUTE_READONLY            = 0x00001
    win32con.FILE_ATTRIBUTE_HIDDEN              = 0x00002
    win32con.FILE_ATTRIBUTE_SYSTEM              = 0x00004
    win32con.FILE_ATTRIBUTE_DIRECTORY           = 0x00010
    win32con.FILE_ATTRIBUTE_ARCHIVE             = 0x00020
    win32con.FILE_ATTRIBUTE_DEVICE              = 0x00040
    win32con.FILE_ATTRIBUTE_NORMAL              = 0x00080
    win32con.FILE_ATTRIBUTE_TEMPORARY           = 0x00100
    win32con.FILE_ATTRIBUTE_ATOMIC_WRITE        = 0x00200
    win32con.FILE_ATTRIBUTE_SPARSE_FILE         = 0x00200
    win32con.FILE_ATTRIBUTE_REPARSE_POINT       = 0x00400
    win32con.FILE_ATTRIBUTE_XACTION_WRITE       = 0x00400
    win32con.FILE_ATTRIBUTE_COMPRESSED          = 0x00800
    win32con.FILE_ATTRIBUTE_OFFLINE             = 0x01000
    win32con.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x02000
    win32con.FILE_ATTRIBUTE_ENCRYPTED           = 0x04000
    win32con.FILE_ATTRIBUTE_VIRTUAL             = 0x10000
_mtypes.CData = _ctypes.Array.__bases__[0]
_mtypes.PPIDLIST_ABSOLUTE = _ctypes.POINTER(_ctypes.c_void_p)
_mtypes.SFGAOF = _wtypes.ULONG
_mtypes.PSFGAOF = _ctypes.POINTER(_mtypes.SFGAOF)
_ole32.CoInitialize.restype = _ctypes.HRESULT # checked
_ole32.CoInitialize.argtypes = (_ctypes.c_void_p,)
_ole32.CoUninitialize.restype = None
_ole32.CoUninitialize.argtypes = ()
_ole32.CoTaskMemFree.restype = None
_ole32.CoTaskMemFree.argtypes = (_ctypes.c_void_p,)
_user32.DestroyIcon.argtypes = (_wtypes.HICON,)
_shell32.SHParseDisplayName.restype = _ctypes.HRESULT # checked
_shell32.SHParseDisplayName.argtypes = (
    _wtypes.LPCWSTR,           # pszName,   _In_
    _ctypes.c_void_p,          # pbc,       _In_opt_
    _mtypes.PPIDLIST_ABSOLUTE, # ppidl,     _Out_
    _mtypes.SFGAOF,            # sfgaoIn,   _In_
    _mtypes.PSFGAOF)           # psfgaoOut, _Out_opt_
class SHFILEINFO(_ctypes.Structure):
   _fields_ = (('hIcon', _wtypes.HICON),
               ('iIcon', _ctypes.c_int),
               ('dwAttributes', _wtypes.DWORD),
               ('szDisplayName', _wtypes.WCHAR * win32con.MAX_PATH),
               ('szTypeName', _wtypes.WCHAR * 80))
_mtypes.SHFILEINFO = SHFILEINFO
_mtypes.PSHFILEINFO = _ctypes.POINTER(SHFILEINFO)
_shell32.SHGetFileInfoW.restype = _ctypes.c_void_p
_shell32.SHGetFileInfoW.argtypes = (
    _wtypes.LPVOID,      # pszPath,          _In_
    _wtypes.DWORD,       # dwFileAttributes,
    _mtypes.PSHFILEINFO, # psfi,             _Inout_
    _wtypes.UINT,        # cbFileInfo,
    _wtypes.UINT)        # uFlags
def SHGetFileInfo(pidl, attributes=0, flags=0):
    if _shell is not None:
        if not isinstance(pidl, (str, bytes, _mtypes.CData)):
            pidl = _shell.PIDLAsString(pidl)
    finfo = SHFILEINFO()
    _ole32.CoInitialize(None)    
    try:
        retval = _shell32.SHGetFileInfoW(pidl,
                                         attributes,
                                         _ctypes.byref(finfo),
                                         _ctypes.sizeof(finfo),
                                         flags)
    finally:
        _ole32.CoUninitialize()
    if not retval:            
        if flags != shellcon.SHGFI_EXETYPE:
            raise _ctypes.WinError()
    return retval, finfo

例:

if __name__ == '__main__':
    import os    
    path = os.path.expanduser(r'~Desktopdesktop.ini')
    pidl = _shell.SHParseDisplayName(path, 0)[0]
    assert isinstance(pidl, list)
    flags = (shellcon.SHGFI_PIDL |
             shellcon.SHGFI_ICON |
             shellcon.SHGFI_DISPLAYNAME |
             shellcon.SHGFI_TYPENAME |
             shellcon.SHGFI_ATTRIBUTES |
             shellcon.SHGFI_SYSICONINDEX)
    hImageList, finfo = SHGetFileInfo(pidl, 0, flags)
    print('hImageList:', hImageList)
    for name, typ in finfo._fields_:
        print(name, ': ', ascii(getattr(finfo, name)), sep='')
    if finfo.hIcon:
        _user32.DestroyIcon(finfo.hIcon)

输出:

hImageList: 4411024
hIcon: 10617107
iIcon: 7
dwAttributes: 1078497655
szDisplayName: 'desktop.ini'
szTypeName: 'Configuration settings'

最新更新