12

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.

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
John Gietzen
  • 48,783
  • 32
  • 145
  • 190

2 Answers2

13

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
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
  • @John: 4 seconds difference :D Guess we both used the same search terms ;) – Niklas B. Apr 04 '12 at 22:55
  • "this was the result of a very quick Google search", only after I phrased the question in such a way as to make the searching easier. I had spent about an hour looking for "make python stop emiting carriage return", and so I came here. – John Gietzen Apr 07 '12 at 19:35
  • @John: Oh, that wasn't meant as an offense, sorry. I've also spent hours researching something, only to finally be pointed to a link which must have been among the first 10 results for *some* of my queries, but which I just happened to not click at. Sometimes it's a matter of luck :) Have fun! – Niklas B. Apr 07 '12 at 21:19
-4

Add 'r' before the string:

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

As expected, it also works for print.

Dominik
  • 377
  • 4
  • 11