printing bytes to stdout in Py3

Casey Caseyweb at gmail.com
Tue Feb 17 11:31:28 EST 2009


On Feb 17, 7:28 am, Christian Heimes <li... at cheimes.de> wrote:
> Peter Billam schrieb:
>
> > Greetings. (Newbie warning as usual) In Python3, sys.stdout is a
> > io.TextIOWrapper object; but I want to output bytes
> >   (e.g. muscript -midi t > t.mid )
> > and they're coming out stringified :-(  How can I either change the
> > encoding on sys.stdout, or close sys.stdout and reopen it in 'b'
> > mode, or dup(fd) it first, or whatever the right thing to do is ?
>
> The official API to write binary data to stdout is:
>
> >>> count = sys.stdout.buffer.write(b"abc\n")
>
> abc
>
> Christian

Is this really the 'official' way to do this?  This isn't meant to be
confrontational or trolling; I honestly don't know the answer and I
had similar questions when I first started with the 3.0 release
candidates and I have yet to find a good answer in the Python v3.0
documentation.  Why wouldn't you just use:

print(bytes.decode(b'abc\n'), end='')



More information about the Python-list mailing list