Python3 buffer extra byte??

D

Dodo

Let's consider this code:

#!/usr/bin/python3
import cgi, sys
print("Content-type:image/jpeg\n\n")
f = open("img.jpg","rb")
sys.stdout.flush()
sys.stdout.buffer.write( f.read() )
f.close()

I receive the file with one padding byte at the start of the file (0x0a)
http://www.1pix.org/multi/images/wg7zg58gsgbhc9cppo5i.jpg

Any idea why?

Dorian
(yes, this is the continuation of "CGI python 3 write RAW BINARY")
 
A

Antoine Pitrou

Let's consider this code:

#!/usr/bin/python3
import cgi, sys
print("Content-type:image/jpeg\n\n")

print() adds an additional \n, so there's one too many.
Also, HTTP headers should be separated with \r\n, not \n.

(besides, under Windows \n will be converted to \r\n by the text I/O
layer, therefore, it would be better to use the binary I/O layer, a.k.a
sys.stdout.buffer, if you want your script to be portable)

Therefore, I would advocate rewriting it as:

sys.stdout.buffer.write(b"Content-type:image/jpeg\r\n\r\n")
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top