Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sys.stdout is opened as text on Windows #1

Open
techtonik opened this issue Oct 8, 2015 · 0 comments
Open

sys.stdout is opened as text on Windows #1

techtonik opened this issue Oct 8, 2015 · 0 comments
Labels

Comments

@techtonik
Copy link
Member

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant