原始模式下的Python在stdin打印中添加空格 [英] Python in raw mode stdin print adds spaces

查看:123
本文介绍了原始模式下的Python在stdin打印中添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Python中将标准输入切换为非缓冲模式,以便可以从中读取单个字符.我设法使其正常工作,但是现在标准输出已损坏:以某种方式在换行符之后发出了一些空格字符,第一行为零,第二行为3,第三行为6,依此类推:

I needed to switch the standard input to non-buffered mode in Python, so that I can read single characters off it. I managed to get it working, but now the standard output is broken: somehow it seems like after the newline character, some space characters are emitted, zero on the first line, 3 on the second, 6 on the third, etc, like this:

ASD
   ASD
      ASD

操作系统是Ubuntu Linux 12.04,64位版本,Python版本是3.2.3.

Operating system is Ubuntu Linux 12.04, 64-bit edition, Python version is 3.2.3.

如何摆脱这种行为?

以下是我使用的代码:

import sys
import tty
import termios

fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin)

for i in range(0, 10):
    print("ASD")

termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

推荐答案

看起来您只在换行,而没有回车.将打印更改为

Looks like you are only doing a line feed but no carriage return. Change your print to

print("ASD", end="\r\n")

这篇关于原始模式下的Python在stdin打印中添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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