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

Discussion in 'Python' started by Evgeni Sergeev, Jan 4, 2005.

  1. 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
     
    Evgeni Sergeev, Jan 4, 2005
    #1
    1. Advertising

  2. Evgeni Sergeev

    Jeff Epler Guest

    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-----
     
    Jeff Epler, Jan 4, 2005
    #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. Mike Finister
    Replies:
    1
    Views:
    749
  2. Mike Finister
    Replies:
    3
    Views:
    477
    Shug Boabie
    Jul 24, 2004
  3. Ferenc Engard
    Replies:
    2
    Views:
    168
  4. James Smith
    Replies:
    3
    Views:
    166
  5. Matt Bleh
    Replies:
    6
    Views:
    173
    David Masover
    Sep 22, 2009
Loading...

Share This Page