Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使Python在向sys.stdout写入换行符时停止发出回车_Python_Windows_Python 2.7 - Fatal编程技术网

使Python在向sys.stdout写入换行符时停止发出回车

使Python在向sys.stdout写入换行符时停止发出回车,python,windows,python-2.7,Python,Windows,Python 2.7,我在Windows上,Python(非常有效地)阻止我向STDOUT发送独立的'\n'字符。例如,以下内容将输出foo\r\nvar: sys.stdout.write("foo\nvar") 如何关闭此“功能”?首先写入文件不是选项,因为输出正在通过管道传输。在写入任何内容之前,请尝试以下操作: import sys if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(),

我在Windows上,Python(非常有效地)阻止我向STDOUT发送独立的
'\n'
字符。例如,以下内容将输出
foo\r\nvar

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

如何关闭此“功能”?首先写入文件不是选项,因为输出正在通过管道传输。

在写入任何内容之前,请尝试以下操作:

import sys

if sys.platform == "win32":
   import os, msvcrt
   msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
如果您只想暂时更改为二进制模式,您可以为自己编写一个包装器:

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时使用的是什么。我的意思是,您使用什么来写入它<代码>打印
sys.stdout.write()“这是一个非常快速的谷歌搜索的结果”,只是在我用一种使搜索更容易的方式表达了这个问题之后。我花了大约一个小时寻找“让python停止发射马车返回”,所以我来到这里。@John:哦,这不是冒犯,对不起。我也花了几个小时研究了一些东西,但最终被指向了一个链接,它肯定是我的一些查询的前10个结果之一,但我只是碰巧没有点击它。有时这是运气的问题:)玩得开心!啊,它会打印反斜杠和n吗?
sys.stdout.write(r"foo\nvar")