Controlling newlines when writing to stdout (no \r\n).

Evgeni Sergeev evgeni_sergeev at hotmail.com
Mon Jan 3 20:47:02 EST 2005


While I can make a verbatim copy of a file like this:

    file1 = file('ready.pdf', 'rb')
    file2 = file('out.pdf', 'wb')

    buffer = file1.read(256)
    while buffer:
	file2.write(buffer)
	buffer = file1.read(256)

    file1.close()
    file2.close()

I cannot send a verbatim copy to stdout. Python replaces
\n with \r\n due to its universal newline support. (This
is on Windows).

My aim is to send a binary file from a CGI python script.
I do this:

    file1 = file('ready.pdf', 'rb')
    
    sys.stdout.write( \
    'Content-type: application/pdf\n' + \
    'Content-disposition: inline; filename=ready.pdf\n\n' + \
    file1.read())

    file1.close()

Checking the traffic with my proxy server reveals that
inside the PDF file, all the \n chars have been replaced
with \r\n.

Is there a way to avoid this intervention?
(I avoided the whole problem by sending a HTTP redirect
'Location: ready.pdf\n\n', but I still want to know the answer).

    Evgeni Sergeev



More information about the Python-list mailing list