For Unix (Old school):
import os
import tempfile
temp = tempfile.mktemp(dir='/tmp')
with open(temp, 'w') as printer:
printer.write('Hello World')
_ = os.system(`lpr {}`.format(temp))
os.unlink(temp)
Для современных Unix всё несколько проще, можно просто дернуть CUPS.
А вообще из всего существующего самые лучшие результаты дает QPrinter из Qt, печатает pdf, ps и html. Т.е. сформировал html и отправил на печать. К тому же кроссплатформенный.
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
from PyQt4 import QtGui, QtWebKit
class Printer(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setWindowTitle('Sample Printer')
self.setMinimumSize(100, 100)
self.print_button = QtGui.QPushButton('Print')
self.close_button = QtGui.QPushButton('Close')
self.layer = QtGui.QHBoxLayout(self)
self.layer.addWidget(self.print_button, 0)
self.layer.addWidget(self.close_button, 1)
self.html = QtWebKit.QWebView()
self.html.setHtml("<h1>Hello World</h1>")
self.print_button.clicked.connect(self.printer)
self.close_button.clicked.connect(self.close)
def printer(self):
self.qprinter = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
self.qprinter.setPageSize(QtGui.QPrinter.A4)
self.qprinter.setOrientation(QtGui.QPrinter.Landscape)
self.dialog = QtGui.QPrintPreviewDialog(self.qprinter)
self.dialog.paintRequested.connect(self.print_preview)
self.dialog.exec_()
def print_preview(self):
self.html.print_(self.qprinter)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
p = Printer()
p.show()
sys.exit(app.exec_())