从 STDIN 读取后,Python 在 `input(...)` 处崩溃 [英] Python crashing at `input(...)` after reading from STDIN

查看:71
本文介绍了从 STDIN 读取后,Python 在 `input(...)` 处崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不会崩溃:

import sys
print(len(sys.stdin.read()))

但这会崩溃:

import sys
print(len(sys.stdin.read()))
input('lol')

带输出

2300
lolTraceback (most recent call last):
  File "test018.py", line 3, in <module>
    input('lol')
EOFError: EOF when reading a line

问题:

  • 为什么?
  • 如何做才是正确的?我的目标是从 STDIN 读取一些数据(例如 cat somefile | myscript),然后提示用户一些问题(例如 嘿,这看起来对吗?).
  • Why?
  • How to do it right? My goal is to read some data from STDIN (e.g. cat somefile | myscript), and then prompt the user on some matter (e.g. hey, does this look right?).

推荐答案

您已经从 stdin 读取到文件末尾,但您可以从终端设备读取:

You have already read from stdin until end of file, but you could read from the terminal device:

import sys
print(len(sys.stdin.read()))

print("lol ", end="")
sys.stdout.flush()
answer = open("/dev/tty").readline().replace("\n", "")
print("You typed:", answer)

如果您也使用管道标准输出,那么您可能希望类似地将提示写入终端设备(请注意,您必须打开它才能写入),尽管此示例使用了普通的 print到标准输出.

If you pipe stdout also, then you would probably want to write the prompt to the terminal device similarly (note that you would have to open it for writing), although this example uses an ordinary print to stdout.

这篇关于从 STDIN 读取后,Python 在 `input(...)` 处崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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