Python3 buffer extra byte??

Discussion in 'Python' started by Dodo, May 17, 2010.

  1. Dodo

    Dodo Guest

    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")
     
    Dodo, May 17, 2010
    #1
    1. Advertising

  2. On Mon, 17 May 2010 20:34:21 +0200
    Dodo <> wrote:

    > 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")
     
    Antoine Pitrou, May 17, 2010
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Union
    Replies:
    2
    Views:
    2,549
    David Union
    Sep 2, 2004
  2. Raja
    Replies:
    12
    Views:
    24,635
    John Harrison
    Jun 21, 2004
  3. Replies:
    2
    Views:
    621
    sergejusz
    Mar 26, 2007
  4. mathieu
    Replies:
    3
    Views:
    620
    Bo Persson
    Sep 4, 2009
  5. Andrew Berg
    Replies:
    0
    Views:
    352
    Andrew Berg
    Jun 16, 2012
Loading...

Share This Page