You want to send binary data, such as for an image, to stdout under Windows.
1 2 3 4 5
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 under Windows, such as for an image, then the file must specifically be opened in binary mode (Unix doesn't make a distinction between text and binary modes). But this is a problem for a program that wants to write binary data to standard output (as a web CGI program would be expected to do), since the 'sys' module opens the 'stdout' file object on your behalf and normally does so in text mode. You could have 'sys' open 'stdout' in binary mode instead by supplying the '-u' command-line option to the Python interpreter. But if you want to control this mode from within a program, then (as shown in the code sample) you can use the 'setmode' function provided by the Windows-specific 'msvcrt' module to change the mode of stdout's underlying file descriptor.
This works for me, no need for msvcrt (which is not available on Cygwin, but you still get problems)
PS: More extended example.