微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。