Skip to content Skip to sidebar Skip to footer

Make Python Stop Emitting A Carriage Return When Writing Newlines To Sys.stdout

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.wri

Solution 1:

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

@contextmanagerdefbinary_mode(f):
   if sys.platform != "win32":
      yield; returnimport msvcrt, os
   defsetmode(mode):
      f.flush()
      msvcrt.setmode(f.fileno(), mode)

   setmode(os.O_BINARY)
   try:
      yieldfinally:
      setmode(os.O_TEXT)

with binary_mode(sys.stdout), binary_mode(sys.stderr):
   # code

Solution 2:

Add 'r' before the string:

sys.stdout.write(r"foo\nvar")

As expected, it also works for print.

Post a Comment for "Make Python Stop Emitting A Carriage Return When Writing Newlines To Sys.stdout"