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

E

Evgeni Sergeev

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
 
J

Jeff Epler

Well, here's the first page turned up by google for the terms 'python
binary stdout':
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65443


Code from that page:
import sys

if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

Thanks, Google & the Python Cookbook website!

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFB2fm1Jd01MZaTXX0RAoe/AJ0ZxufcwaA2efaQFsmJoX15uykOtgCeKAPA
FfccLcye/ave6u1HESzuNME=
=wLwt
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top