Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...