使用 Python 获取 OS X 中所有可用的打印机



目前我正在用Python中的打印机进行一些测试,我试图做的是列出所有可用的打印机。

现在我正在使用 PyCups 库,它在Connection类中公开了几个有用的 API。其中还有getPrinters()

这是我使用和工作的片段:

>>> import cups
>>> conn = cups.Connection ()
>>> printers = conn.getPrinters ()
>>> for printer in printers:
...     print printer, printers[printer]["device-uri"]
Brother_MFC_1910W_series
Photosmart_6520_series

我想知道是否有任何方法可以在不使用任何外部库的情况下编写上述代码。我很确定如果不使用 C,这是不可能的。

任何对文档的建议或参考将不胜感激。谢谢

我正在使用Python 3

只能

将 Python 中的 C 库与标准模块一起使用。参考资料:CUPS API,ctypes。将 CUPS 结构和调用转换为ctypes语法,我们得到的代码可以在标准 OS X Python 和 Python 3 下工作:

from __future__ import print_function
from ctypes import *

class cups_option_t(Structure):
    _fields_ = [
        ('name', c_char_p),
        ('value', c_char_p)
    ]

class cups_dest_t(Structure):
    _fields_ = [
        ('name', c_char_p),
        ('instance', c_char_p),
        ('is_default', c_int),
        ('num_options', c_int),
        ('cups_option_t', POINTER(cups_option_t))
    ]

cups_lib = cdll.LoadLibrary('/usr/lib/libcups.dylib')

if __name__ == '__main__':
    dests = cups_dest_t()
    dests_p = pointer(dests)    
    num_dests = cups_lib.cupsGetDests(byref(dests_p))    
    for i in range(num_dests):
        dest = dests_p[i]
        print(dest.is_default, dest.name)
        for j in range(dest.num_options):
            option = dest.cups_option_t[j]
            print('', option.name, option.value, sep='t')    
    cups_lib.cupsFreeDests(num_dests, dests_p)

使用ctypes时要特别小心,大多数错误会产生分割错误。

您可以使用

终端命令lpstat(man for OSX)执行类似的查询。Python 的内置subprocess模块将允许您运行该命令并存储输出。某些文本分析应提供打印机名称。

from subprocess import Popen, PIPE
# "lpstat -a" prints info on printers that can accept print requests
p = Popen(['lpstat', '-a'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, errors = p.communicate()
lines = output.split('n')
# check before you implement this parsing
printers = map(lambda x: x.split(' ')[0], lines)

最新更新