Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

windows - 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 ' ' character to STDOUT. For example, the following will output foo var:

sys.stdout.write("foo
var")

How can I turn this "feature" off? Writing to a file first is not an option, because the output is being piped.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...