Python的默认行为会占用所有输入行,而EOFError留给下一个脚本

问题描述

Python似乎是输入行的贪婪的接受者?

非常简单的python3脚本:testinput.py

for i in range(5):
    x = input()
    print(f'{i}. {x}')

Python脚本被Bash脚本反复调用:testinput.sh

python3 testinput.py
python3 testinput.py
python3 testinput.py

输入文件:testinput.txt

wo
wajf
wajf
jwfao
ksd
3
34
35
w45
54w
seg
jawfo
34j
serg
se
se
gser
gg
erg
segrse
rg
g
esg
g
g
erg
serg
serg
seg
:wq

现在我将testinput.txt馈送到testinput.sh:

bash testinput.sh < testinput.txt

我得到:

0. wo
1. wajf
2. wajf
3. jwfao
4. ksd
Traceback (most recent call last):
  File "testinput.py",line 2,in <module>
    x = input()
EOFError: EOF when reading a line
Traceback (most recent call last):
  File "testinput.py",in <module>
    x = input()
EOFError: EOF when reading a line

如何使python3的每次调用仅采用所需的输入行?谢谢! (已在Ubuntu和Cygwin中进行过测试,因此不太可能依赖于平台)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)