2011-03-17

Printing Via LPR

If you have a Python app, or almost any kind of app, the accepted manner for printing is to use some kind of subprocess to invoke some command-line utility to submit the print job.  Of course this requires that the underlying subsystems are aware of printers [and thus run a printer subsystem].  It also assumes the name of the command-line utility, the permissions are adequate to execute it, and all manner of other things.  To put it simply: this is terrible!  Why does my web server, workflow server, etc... need to run a print service?  Why can't my environment just support submitting a job to an actual print server?  Good question!  To answer this OpenGroupware Coils now has a simple implementation of the LPR/LPD protocol.  This code is under the MIT/X11 license so you are free to copy-and-paste it into your own application.  Sending a job to the server is as simple as:

f = open('Draft.ps', 'rb')
pr = LPR('crew.mormail.com', user='adam')
lpr.connect()
lpr.send_stream('cisps', 'test job', f, job_name='my awesome job')
lpr.close()
f.close()

This sends the contents of the file "Draft.ps" to the printer "cisps" on the LPD server "crew.mormail.com" with user name "adam", job name "my awesome job" and job file name "test job".

The code for the LPR class can be found here.