Is there any way to write binary output to sys.stdout in Python 2.x? In Python 3.x, you can just use sys.stdout.buffer (or detach stdout, etc...), but I haven't been able to find any solutions for Python 2.5/2.6.
EDIT: I'm trying to push a PDF file (in binary form) to stdout for serving up on a web server. When I try to write the file using sys.stdout.write, it adds all sorts of carriage returns to the binary stream that causes the PDF to render corrupt.
EDIT 2: For this project, I need to run on a Windows Server, unfortunately, so Linux solutions are out.
Simply Dummy Example (reading from a file on disk, instead of generating on the fly, just so we know that the generation code isn't the issue):
file = open('C:\\test.pdf','rb')
pdfFile = file.read()
sys.stdout.write(pdfFile)
sys.stdout.write()
what didn't work? – Vicarialsys.stdout = os.fdopen(1, "wb")
work for you to eliminate text-mode conversions? (You'll still need to use sys.stdout.write if you don't want the NLs from print statements.) (docs.python.org/library/os.html#os.fdopen) – Supernatantos.fdopen
doesn't solve it, although running python with the-u
works.-u
does bring extra overhead though – Morningsos.write()
andos.read()
seems to be working fine in my test cases. – Charmeuse