[英]python 2 stdin can't read individual lines
我有以下非常簡單的代碼:
from __future__ import print_function
import sys
for line in sys.stdin:
print("hello!")
sys.stdout.flush()
當我運行它時,我希望輸入一行然后立即打個hello!
在它后面打印出來,然后我可以輸入另一行。
當我用py -3
運行它時,我得到預期的結果:
py -3 test.py
asdf
hello!
asdf
hello!
asdf
hello!
^C
當我用py -2
運行它時,它不會打個hello!
除非我發送ctrl-Z:
py -2 test.py
asdf
asdf
asdf
^Z
hello!
hello!
hello!
asdf
^Z
hello!
^Z
我在帶有Python 2.7.12的Windows上和在帶有Python 2.6.6的Linux(使用ctrl-D而不是ctrl-Z)上運行了該測試。
如何獲得與Python3相匹配的Python 2行為?
在repl.it上工作的Python 3示例: https ://repl.it/Cs6n/0
在repl.it上損壞的Python 2示例: https ://repl.it/Cs7C/0
您的問題的答案在這里禁用輸出緩沖 。 (已接受答案的第4條評論)。 您的工作代碼應如下所示:
from __future__ import print_function
import sys
while True:
line = sys.stdin.readline()
print("hello!")
在python 2.7.11中完美工作
編輯 : sys.stdout.flush()
最后一行已被刪除。 在這種情況下,無需使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.