can you print a file from python?

后端 未结 3 1932
清歌不尽
清歌不尽 2020-12-19 19:39

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? Mayb

3条回答
  •  生来不讨喜
    2020-12-19 20:18

    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.

提交回复
热议问题