是否可以在Windows中获取打印机名称列表?

时间:2012-04-11 15:25:14

标签: python windows

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

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

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

1 个答案:

答案 0 :(得分:4)

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

这是一个完全正常的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)