将换行符写入 sys.stdout 时,使 Python 停止发出回车符 [英] Make Python stop emitting a carriage return when writing newlines to sys.stdout

查看:51
本文介绍了将换行符写入 sys.stdout 时,使 Python 停止发出回车符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Windows,而 Python(非常有效地)阻止了我向 STDOUT 发送独立的 '\n' 字符.例如,以下将输出 foo\r\nvar:

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.

推荐答案

在写任何东西之前尝试以下操作:

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

这篇关于将换行符写入 sys.stdout 时,使 Python 停止发出回车符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆