Sending Binary Data to Standard Output Under Windows

Credit: Hamish Lawson

Problem

You want to send binary data (e.g., an image) to stdout, under Windows.

Solution

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)

Discussion

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.

See Also

Documentation for the msvcrt module in the Library Reference.

Get Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.