[Tutor] Printing data to a printer...

Rich Lovely roadierich at googlemail.com
Sat Jan 2 21:19:16 CET 2010


2010/1/2 Ken G. <beachkid at insightbb.com>:
> Wow, I looked and looked.  I can print out my program listing but can not
> print the resulted data produced by the program.
>
> How do I print out on my USB printer the data output of my Python program I
> ran in my Ubuntu terminal via Geany IDE?
> I already wrote several programs using raw_input, files, sort, list, tuple
> and I like Python!  Currently, I'm using Python 2.6.  In Liberty Basic, the
> command was lprint.  For example:
>
>   print 2 + 2    #    display in terminal
>
>   lprint 2 + 2    #   print result to printer
> TIA,
>
> Ken
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

There doesn't appear to be anything builtin to make it easy - on
Linux, at least.  There are three options, as far as I can see.  I
don't have a printer, so can't test either.

First is to pipe the output from the program to a command line
printing program.  This will mean that all of the data written to
stdout is sent straight to the printer.  This can only be done at the
command line, and will look something like
$ python your_program.py | lpr

Using this method, you can still send output to the console using
sys.stderr.write()

This is the traditional unix method, but is only really appropriate
for your own scripts.

The second option is to open a pipe to a program such as lpr from
within python, using the subprocess module:

import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(data_to_print)

The third option is to use a third party library.  The current linux
printing system is called CUPS, so you can try searching the
cheeseshop (pypi.python.org) or google for python cups packages.  The
pypi gives one possibility:  http://www.pykota.com/software/pkipplib

There is a fourth option, which might not even work: opening the
printer device as a file-like object (I don't recommend trying this
without doing a lot of research first):

lp = open("/dev/lp0", "w")
lp.write(data_to_print)

Of course, all of this is very much os specific.  The first option
will work in linux, osx and windows, but two and three will only work
in linux and osx, however printing is considerably easier on windows,
there is the win32print package that does (most of) the heavy lifting
for you.  To be honest, I'm not even sure if option four will work
_at_all_.

-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.


More information about the Tutor mailing list