Sending binary data through stdout on Windows

It looks like I’m not the first one stumbling over this, but I just had a lot of fun trying to figure out why a moderately complex binary protocol sometimes randomly failed to work when sent through a subprocess stdout pipe. Apparently, because Python opens Windows stdout in text mode, something like “x0A” ended up as “x0Dx0A” on the receiving end.

Even worse, when trying to debug it by dumping stuff to files, I forgot to open those in binary mode too, which made things even more confusing 😉

Here’s the solution:

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s