Credit: Hamish Lawson
That’s what the setmode
function,
in the platform-dependent msvcrt
module in
Python’s standard library, is for:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno( ), os.O_BINARY)
If you are reading or writing binary data, such as an image, under
Windows, the file must be opened in binary mode (Unix
doesn’t make a distinction between text and binary
modes). However, this is a problem for programs that write binary
data to standard output (as a CGI program could be expected to do),
because Python opens the sys.stdout
file object on
your behalf, normally in text mode.
You can have stdout
opened in binary mode instead
by supplying the -u
command-line option to the Python
interpreter. However, if you want to control this mode from within a
program, you can use the
setmode
function provided by the
Windows-specific msvcrt
module to change the mode of
stdout
’s underlying file
descriptor, as shown in the recipe.