[英]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.我在 Windows 和 Python 上(非常有效地)阻止我向 STDOUT 发送独立的
'\n'
字符。 For example, the following will output foo\r\nvar
:例如,以下将 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.
首先写入文件不是一种选择,因为 output 正在通过管道传输。
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
Add 'r' before the string : 在字符串前添加 'r' :
sys.stdout.write(r"foo\nvar")
As expected, it also works for print.正如预期的那样,它也适用于打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.