sys.stdin 和 input() 之间的冲突 - EOFError: 读取一行时出现 EOF

2024-04-01

我无法让以下脚本在不引发 EOFError 异常的情况下工作:

#!/usr/bin/env python3

import json
import sys

# usage:
# echo '[{"testname": "testval"}]' | python3 test.py

myjson = json.load(sys.stdin)
print(json.dumps(myjson))

answer = input("> ")  # BUG: EOFError: EOF when reading a line
print(answer)

我读过这个似乎相关的问题:Python STDIN 用户输入问题 https://stackoverflow.com/questions/35018268/python-stdin-user-input-issue

我认为这告诉我我需要清除标准输入缓冲区?但我不知道怎么因为print(sys.stdin.readline())只是输出一个换行符并且 EOFError 仍然存在。

我也尝试使用sys.stdin.flush()方法(在这个问题中找到:sys.stdout.flush() 方法的用法 https://stackoverflow.com/questions/10019456/usage-of-sys-stdout-flush-method#10019605)虽然我仍然不明白它的作用,因为我在官方文档(3.6)中找不到它,但我找到的最接近的是这个,但它没有提到刷新:https://docs.python.org/3/library/sys.html https://docs.python.org/3/library/sys.html

请记住,我不是程序员,也没有计算机科学教育或背景。我只是编写脚本来自动化部分非技术性工作。因此,如果您知道有关 stdin/stdout 如何在 Python 的 shell 中工作的任何好的初学者资源,请告诉我们。


通过管道输入,Python 将 sys.stdin 作为 FIFO 打开。否则,Python 将打开 sys.stdin/dev/tty或同等学历。

您可以通过以下方式验证这一点:

import os,sys,stat
print("isatty():", sys.stdin.isatty())
print("isfifo():", stat.S_ISFIFO(os.fstat(0).st_mode))

运行两次,一次输入数据,一次不输入。

I get:

$ echo "Test" | ./test2.py
isatty(): False
isfifo(): True

$ ./test2.py
isatty(): True
isfifo(): False

所以你的 EOF 发生是因为 FIFO sys.stdin 打开到is empty.

您可以重新打开 sys.stdin 来/dev/tty, 然而。

j = json.load(sys.stdin)
print(j)

sys.stdin = open("/dev/tty")

answer = input("> ")
print(answer)

哪个会工作得很好:

$ echo '{"key":"val"}' | python3 ./testjson.py
{'key': 'val'}
> testing
testing
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

sys.stdin 和 input() 之间的冲突 - EOFError: 读取一行时出现 EOF 的相关文章

随机推荐