Writing binary to stdout

Paul Watson pwatson at redlinepy.com
Thu Jun 24 09:47:28 EDT 2004


"Chris King" <squirrel at wpi.edu> wrote in message
news:10dk8nbr1m51k04 at corp.supernews.com...
> Paul Watson wrote:
> > Even when I try to use low-level I/O it does CRLF interpretation.  What
am I
> > doing wrong?
>
> Are you using Cygwin? It will automatically CRLFify anything it thinks
> should be (I'm not sure what the exact critera are); this has bit me
> before, too. There's an option to disable it in Cygwin setup. This is
> being passed on to the script because the stdout redirections are done
> in Cygwin, not in Python.

The following appears to work under 2.1 in Cygwin and 2.3.4 under a DOS box.
I did not change any Cygwin setting.  Is there anything undesireable in the
code below?  The intent is to say if this is running on Windows, set stdout
to binary mode.

Am I safe in assuming that 'import msvcrt' will fail on all other machines?
Is there a better way?

$ cat ./wb.py
#! /usr/bin/env python
import sys
import os

try:
    import msvcrt
    msvcrt.setmode(1, os.O_BINARY)
except:
    pass

sys.stdout.write("now\n")
print "and then"

$ ./wb.py >jjj

$ od -c jjj
000000 6e 6f 77 0a 61 6e 64 20 74 68 65 6e 0a
         n   o   w  \n   a   n   d       t   h   e   n  \n
00000d





More information about the Python-list mailing list