I'm on Windows and Python is (very effectively) preventing me from sending a stand-alone '\n'
character to STDOUT. For example, the following will output foo\r\nvar
:
sys.stdout.write("foo\nvar")
How can I turn this "feature" off? Writing to a file first is not an option, because the output is being piped.
Try the following before writing anything:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
If you only want to change to binary mode temporarily, you can write yourself a wrapper:
import sys
from contextlib import contextmanager
@contextmanager
def binary_mode(f):
if sys.platform != "win32":
yield; return
import msvcrt, os
def setmode(mode):
f.flush()
msvcrt.setmode(f.fileno(), mode)
setmode(os.O_BINARY)
try:
yield
finally:
setmode(os.O_TEXT)
with binary_mode(sys.stdout), binary_mode(sys.stderr):
# code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With