Skip to content

sys.stdout is opened as text on Windows #1

@techtonik

Description

@techtonik

On Windows, if you try to pipe binary data from Python into external file, the file will be broken, because all linefeed characters \n will be converted to \n\r.

test1.py:

import sys
bindata = "_\x0a_"
sys.stdout.write(bindata)
> python test1.py > data.bin
> python -c "print(len('_\x0a_'))"
3
> python -c "print(len(open('data.bin', 'rb').read()))"
4

The fix is to use Windows API to set stdout and stderr streams to binary:

import sys

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions