Use Python to connect to the printer on Windows

To connect to a printer using Python on Windows, you can use the following two methods:

1. Use the win32print library:

import win32print

# 获取默认打印机
default_printer = win32print.GetDefaultPrinter()

# 连接到打印机
printer = win32print.OpenPrinter(default_printer)

# 打印文档
win32print.StartDocPrinter(printer, 1, ('My Document', None, 'TEXT'))
win32print.StartPagePrinter(printer)
win32print.WritePrinter(printer, 'Hello, World!')
win32print.EndPagePrinter(printer)
win32print.EndDocPrinter(printer)

# 关闭打印机连接
win32print.ClosePrinter(printer)

Make sure pywin32the library is installed, you can install it with the following command:

pip install pywin32

2. Using CUPS:

First, make sure the CUPS service is installed. You can then use Python's cupslibraries to connect and control the printer.

Install cupsthe library:

pip install cups

Use the following code to concatenate and print the document:

import cups

# 连接到CUPS服务器
cups_conn = cups.Connection()

# 获取默认打印机
printer_name = cups_conn.getDefault()

# 打印文档
cups_conn.printFile(printer_name, "file.txt", "My Document", {
    
    })

Note that you need to have appropriate permissions to use CUPS. In some cases, you may need to run Python scripts as an administrator or root user.

おすすめ

転載: blog.csdn.net/sinat_35773915/article/details/132362081