linux - 使用 sys.stdin.buffer.read() 后使用 input() 时出现 EOFError

标签 linux python-3.x

我目前正在 linux 上编写一个 python 程序,它将通过 sys.stdin.buffer.read() 接受二进制流,然后我希望它在之后使用 input() 以交互方式接受输入.

这是一个完全人为的例子来说明我的问题:

#!/usr/bin/env python3
import sys 

buf = b"Garbage Data"
#comment out the following line to avoid the EOFError:
buf = sys.stdin.buffer.read()

with open("outTempFile", 'wb') as f:
    f.write(buf)

print("Please enter your name:")
buf2 = input("First:\t")
print("Your first name is:\t{}".format(buf2))

当我使用 stdin 输入运行这个程序时,我得到以下错误/输出:

-> % cat contrivedExample.py | ./contrivedExample.py Please enter your name: First: Traceback (most recent call last): File "./contrivedExample.py", line 11, in <module> buf2 = input("First:\t") EOFError: EOF when reading a line

输出文件,outTempFile确实被写入,但是调用input()失败并返回 EOFError .我猜这是因为 STDIN绑定(bind)到我在脚本的命令行调用中使用的管道。

当我注释掉第 6 行并使用相同的调用运行程序时:

-> % cat contrivedExample.py | ./contrivedExample.py

我得到以下输出:

Please enter your name: First: Your first name is: #!/usr/bin/env python3

这告诉我input()确实在读STDIN来自命令行上提供的管道 ( |)。

我的问题是如何将程序从通过管道 ( | ) 读取切换为通过交互式终端提示读取(通常通过 input() 完成)?

最佳答案

我找到的解决方案是在通过 linux 管道 (|) 从 STDIN 读取后简单地将 sys.stdin 替换为 open('/dev/tty ') 允许 input() 从我的终端读取:

echo "hello" | python -c 'import sys; buf = sys.stdin.read(); print(buf); sys.stdin=open("/dev/tty"); buf2=input(); print(buf2)'

关于linux - 使用 sys.stdin.buffer.read() 后使用 input() 时出现 EOFError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40270252/

相关文章:

python - 使用Python返回字典文本文件列表中最大字段的行?

linux - 使用哪种 Linux IPC 技术?

linux - grep 查找 OR 条件下的 2 个单词并打印下 10 行

python-3.x - 定义以数字开头的函数名(在 Python 3 中)?

python - 如何在 python 脚本末尾启动 REPL?

python - 我尝试将 Tkinter 按钮绑定(bind)到键盘上的 Enter 键,但它不起作用

python - 获取集合中不包括某些元素的元素

java - java 的 strace 或 procmon 等效项

linux - Rsync 图像序列的一部分

linux - Ubuntu 从文本文件中获取句子中的最后一个词