Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 445
John Gietzen Avatar asked Apr 04 '12 22:04

John Gietzen


1 Answers

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
like image 83
Niklas B. Avatar answered Oct 08 '22 03:10

Niklas B.