Python 2.x – Write binary output to stdout?

Which platform are you on?

You could try this recipe if you’re on Windows (the link suggests it’s Windows specific anyway).

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

There are some references on the web that there would/should be a function in Python 3.1 to reopen sys.stdout in binary mode but I don’t really know if there’s a better alternative then the above for Python 2.x.

Leave a Comment