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. Advertisements

  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. Advertisements

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,749
    David Union
    Sep 2, 2004
  2. Raja
    Replies:
    12
    Views:
    26,167
    John Harrison
    Jun 21, 2004
  3. Replies:
    2
    Views:
    530
    Karl Heinz Buchegger
    Jan 12, 2005
  4. Replies:
    4
    Views:
    729
  5. Replies:
    2
    Views:
    824
    sergejusz
    Mar 26, 2007
  6. Neal Becker

    buffer creates only read-only buffer?

    Neal Becker, Jan 8, 2009, in forum: Python
    Replies:
    0
    Views:
    575
    Neal Becker
    Jan 8, 2009
  7. mathieu
    Replies:
    3
    Views:
    947
    Bo Persson
    Sep 4, 2009
  8. xingye
    Replies:
    9
    Views:
    554
    Michael Lu
    Apr 19, 2004
Loading...