Timothy Lawman
Timothy Lawman

Reputation: 2312

can you print a file from python?

Is there some way of sending output to the printer instead of the screen in Python? Or is there a service routine that can be called from within python to print a file? Maybe there is a module I can import that allows me to do this?

Upvotes: 2

Views: 10842

Answers (3)

abarnert
abarnert

Reputation: 365945

Most platforms—including Windows—have special file objects that represent the printer, and let you print text by just writing that text to the file.

On Windows, the special file objects have names like LPT1:, LPT2:, COM1:, etc. You will need to know which one your printer is connected to (or ask the user in some way).

It's possible that your printer is not connected to any such special file, in which case you'll need to fire up the Control Panel and configure it properly. (For remote printers, this may even require setting up a "virtual port".)

At any rate, writing to LPT1: or COM1: is exactly the same as writing to any other file. For example:

with open('LPT1:', 'w') as lpt:
    lpt.write(mytext)

Or:

lpt = open('LPT1:', 'w')
print >>lpt, mytext
print >>lpt, moretext
close(lpt)

And so on.

If you've already got the text to print in a file, you can print it like this:

with open(path, 'r') as f, open('LPT1:', 'w') as lpt:
    while True:
        buf = f.read()
        if not buf: break
        lpt.write(buf)

Or, more simply (untested, because I don't have a Windows box here), this should work:

import shutil
with open(path, 'r') as f, open('LPT1:', 'w') as lpt:
    shutil.copyfileobj(f, lpt)

It's possible that just shutil.copyfile(path, 'LPT1:'), but the documentation says "Special files such as character or block devices and pipes cannot be copied with this function", so I think it's safer to use copyfileobj.

Upvotes: 4

Pykler
Pykler

Reputation: 14865

If you are on linux, the following works if you have your printer setup and set as your default.

from subprocess import Popen
from cStringIO import StringIO

# place the output in a file like object
sio = StringIO(output_string)

# call the system's lpr command
p = Popen(["lpr"], stdin=sio, shell=True)
output = p.communicate()[0]

Upvotes: 1

James Polley
James Polley

Reputation: 8181

Python doesn't (unless you're using graphical libraries) ever send stuff to "The screen". It writes to stdout and stderr, which are, as far as Python is concerned, just things that look like files.

It's simple enough to have python direct those streams to anything else that looks like a file; for instance, see Redirect stdout to a file in Python?

On unix systems, there are file-like devices that happen to be printers (/dev/lp*); on windows, LPT1 serves a similar purpose.

Regardless of the OS, you'll have to make sure that LPT1 or /dev/lp* are actually hooked up to a printer somehow.

Upvotes: 1

Related Questions