faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

25 of 25 people (100%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

Printing from Python on Windows

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 361, David Stegbauer


"""
Packages: operating_systems.windows
"""
"""
>In Linux I use the following to redirect printing to
>the printer:
>
>    drukker = sys.stdout
>    drukker = os.popen('lpr','w')
>    drukker.write(drukstuk)
>    sys.stdout.write(drukstuk)
>
>What would the windows equivalent be?
>
> I have tried os.popen('prn', 'w'), but without success.
Printing under windows is not such easy. I personally write to a file, then I
pass it to MS Word to print. I format the output using RTF, but I think there is
no problem to use HTML and Netscape - then it is sufficient to spawn it like
from os import spawnv, P_NOWAIT
spawnv(P_NOWAIT, r'D:\APP\NETSCAPE\PROGRAM\NETSCAPE.EXE', ('NETSCAPE.EXE',
'/print("filename.html")'))
David
"""
# 8<---------------print-word.py--------------------
import struct
from time import sleep
from os import spawnv, P_NOWAIT
from dynwin import windll, windde
def PrintUsingWinWord(filename):
    app = r"C:\MSOFFICE\WINWORD\WINWORD.EXE"
    spawnv(P_NOWAIT, app, (app, "/n"))
    print 'spawned WinWord, sleeping 5 seconds'
    sleep(5)
    s = windde.dde_session()
    s.initialize()
    CC = windll.membuf(36)
    CC.write(struct.pack ('l',36) + (32 * '\000'))
    retries = 10
    while retries:
        try:
            s.connect('WinWord', 'System', CC)
            s.execute('[FileOpen("' + filename + '")]')
            #s.execute('[FilePrint 0][FileExit 2]')
            s.uninitialize()
            retries = 0
        except:
            print 'Unable to connect to WinWord, remain', retries, 'attempts'
            print 'sleeping 10 seconds'
            sleep(10)
            retries = retries - 1
    del s
    return