def binary_stdout ( ) : # First there is a Python3 issue. try : stdout = sys . stdout . buffer except AttributeError : # Probably Python 2, where bytes are strings. stdout = sys . stdout # On Windows the C runtime file orientation needs changing. if sys . platform == "win32" : import msvcrt import os msvcrt . setmode ( sys . stdout . fileno ( ) , os . O_BINARY ) return stdout
python check whether stdout is binary
A sys . stdout that accepts bytes .
def binary_stdout():
    """
    A sys.stdout that accepts bytes.
    """

    # First there is a Python3 issue.
    try:
        stdout = sys.stdout.buffer
    except AttributeError:
        # Probably Python 2, where bytes are strings.
        stdout = sys.stdout

    # On Windows the C runtime file orientation needs changing.
    if sys.platform == "win32":
        import msvcrt
        import os
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

    return stdout