Python sys.stdin.read(1) 在 while(True) 循环中持续执行 1 次获取输入和多次未获取输入

标签 python python-2.7

我在 64 位 Windows 7 上运行 python 2.7。

这是我正在执行的代码:

import sys
while True:
    print 'please enter a character:'
    c = sys.stdin.read(1)
    print 'you entered', str(c)

在 eclipse 的 PyDev 环境中,输入 a 和 b 得到以下输出。

please enter a character:
a
you entered a
please enter a character:
you entered 
please enter a character:
you entered 

please enter a character:
b
you entered b
please enter a character:
you entered 
please enter a character:
you entered 

please enter a character:

它正确地获取一次输入,然后跳过用户输入执行两次。

现在,当我在 python 终端中为输入 a 和 b 运行相同的代码时,我得到以下输出:

enter char
a
you entered a
enter char
you entered

enter char
b
you entered b
enter char
you entered

enter char

这会在获取用户输入和跳过用户输入时执行。

什么会导致这个问题?如何让 Python 在无限循环中一次读取一个字符?

最佳答案

问题可能是由于 \n 持续存在而刷新了标准输入。

作为替代方案,使用 raw_input

while True:
    c = raw_input('please enter a character: ')
    print 'you entered', c

冲洗部分见this

关于Python sys.stdin.read(1) 在 while(True) 循环中持续执行 1 次获取输入和多次未获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15465089/

相关文章:

python - Redshift + SQLAlchemy 长查询挂起

Python - 对列中的数据进行聚类

python - 如何使用循环将文件导入 pandas?

python-2.7 - 在 Python 2.7 和 Python 3.4 中带有内存 View 的 Ctypes from_buffer

python - 类型错误 : <lambda>() takes exactly 1 argument (3 given)

python: importlib.import_module ("time") 但时间没有全局定义

python - Spark (2.2) 性能 <-> Spark 持久

Python 子进程命令执行卡住

python - 为什么不同的Python模块安装在不同的位置?

python - 读取 Python 的 memory_profiler 的输出