2

我正在尝试为 Windows 创建一个自动打印机安装程序。

如果我想提取打印机列表,我将如何在 Python 中进行呢?我知道有一种方法可以在命令行上使用 VB 脚本获取列表,但这给了我不需要的额外信息,而且没有真正的好方法可以将数据导入 Python(我知道)

这样做的原因是获取值并将它们放在一个列表中,然后让它们检查另一个列表。一个列表中的任何内容都将被删除。这可确保程序不会安装重复的打印机。

4

1 回答 1

5

您可以使用pywin32win32print.EnumPrinters()(更方便),或EnumPrinters()通过模块调用 API ctypes(低依赖性)。

这是一个完全工作的ctypes版本,没有错误检查。

# Use EnumPrintersW to list local printers with their names and descriptions.
# Tested with CPython 2.7.10 and IronPython 2.7.5.

import ctypes
from ctypes.wintypes import BYTE, DWORD, LPCWSTR

winspool = ctypes.WinDLL('winspool.drv')  # for EnumPrintersW
msvcrt = ctypes.cdll.msvcrt  # for malloc, free

# Parameters: modify as you need. See MSDN for detail.
PRINTER_ENUM_LOCAL = 2
Name = None  # ignored for PRINTER_ENUM_LOCAL
Level = 1  # or 2, 4, 5

class PRINTER_INFO_1(ctypes.Structure):
    _fields_ = [
        ("Flags", DWORD),
        ("pDescription", LPCWSTR),
        ("pName", LPCWSTR),
        ("pComment", LPCWSTR),
    ]

# Invoke once with a NULL pointer to get buffer size.
info = ctypes.POINTER(BYTE)()
pcbNeeded = DWORD(0)
pcReturned = DWORD(0)  # the number of PRINTER_INFO_1 structures retrieved
winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, Name, Level, ctypes.byref(info), 0,
        ctypes.byref(pcbNeeded), ctypes.byref(pcReturned))

bufsize = pcbNeeded.value
buffer = msvcrt.malloc(bufsize)
winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, Name, Level, buffer, bufsize,
        ctypes.byref(pcbNeeded), ctypes.byref(pcReturned))
info = ctypes.cast(buffer, ctypes.POINTER(PRINTER_INFO_1))
for i in range(pcReturned.value):
    print info[i].pName, '=>', info[i].pDescription
msvcrt.free(buffer)
于 2012-04-11T15:53:40.367 回答