Writing binary to stdout

Paul Watson pwatson at redlinepy.com
Wed Jun 23 17:36:19 EDT 2004


"Christopher T King" <squirrel at WPI.EDU> wrote in message
news:Pine.LNX.4.44.0406231449410.22670-100000 at ccc8.wpi.edu...
>
> On Wed, 23 Jun 2004, Reinhold Birkenfeld wrote:
>
> > Paul Watson wrote:
> > > How can I write lines to stdout on a Windows machine without having
'\n'
> > > expanded to '\r\n'.
> > >
> > > I need to do this on Python 2.1 and 2.3+.
> > >
> > > I see the msvcrt.setmode function.  Is this my only path?  Is it valid
to
> > > change the mode of stdout?  The file.newlines is not writable.
> >
> > What about opening the file in binary mode? This should give you control
> > over the line endings.
>
> Believe it or not, open('CON:','wb') actually works under WinXP. It's
> amazing that this relic from DOS is still around. Though unportable (the
> Unix equivalent is open('/dev/stdout','wb')) and ugly, it'll get the job
done.
>
> Optimally, you'd want to use something like C's freopen to re-open
> sys.stdout in binary mode, but I can't find anything like it under the os
> module. Does Python not have this ability?

This will be a command to run a python script from inside another tool.
 It -must- write to stdout.  Also, Cygwin is on the machine.

Even when I try to use low-level I/O it does CRLF interpretation.  What am I
doing wrong?

pwatson [ watsonp:/cygdrive/c/src/projects/pwatson/bin ] 22
$ cat ./wb.py
#! /usr/bin/env python
import sys
import os

try:
    import msvcrt
    f = os.open(1, 'wb')
except:
    f = sys.stdout

f.write("now\n")
f.close()

sys.exit(0)
pwatson [ watsonp:/cygdrive/c/src/projects/pwatson/bin ] 23
$ ./wb.py >jjj
pwatson [ watsonp:/cygdrive/c/src/projects/pwatson/bin ] 24
$ od -c jjj
000000 6e 6f 77 0d 0a
         n   o   w  \r  \n
000005





More information about the Python-list mailing list