gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:36 24 4
gpt4 key购买 nike

目前我正在用 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 时要特别小心,大多数错误都会产生段错误。

关于python - 使用 Python 获取 OS X 中所有可用的打印机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41514447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com