我目前正在 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/