Make Python stop emitting a carriage return when writing newlines to sys.stdout

Go To StackoverFlow.com

11

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.

2012-04-04 22:45
by John Gietzen
What code are you currently using - Amber 2012-04-04 22:47
Whatever sys.stdout is opened with - John Gietzen 2012-04-04 22:50
I meant what are you using to write to it? print? sys.stdout.write() - Amber 2012-04-04 22:50
Both have the same effect - John Gietzen 2012-04-04 22:52


12

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
2012-04-04 22:53
by Niklas B.
Yep, I just found that too - John Gietzen 2012-04-04 22:54
@John: 4 seconds difference :D Guess we both used the same search terms ; - Niklas B. 2012-04-04 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 2012-04-07 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. 2012-04-07 21:19


-4

Add 'r' before the string:

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

As expected, it also works for print.

2012-04-06 22:55
by Dominik
Ahm, it will print the backslash and the n literally - Niklas B. 2012-04-25 15:18
Ads