我在 python 中撰寫了一些代碼來讀取標準輸入。當我執行它并輸入我想要的所有資料時,我按 Ctrl-D,它應該發送 EOF 宏,但實際上什么也沒發生。我在 arch-linux 上使用 alacritty 終端和 zsh shell 如果那是相關的。
from sys import stdin, stdout
bl = False
res = ""
for line in stdin:
while line:
if bl:
bl = False
arr = list(map(int, line.strip().split(" ")))
dicc = {arr.index(x) : x for x in arr}
for key, value in dicc.items():
res = "{}:{} ".format(key, value)
else:
bl = True
stdout.write(res)
uj5u.com熱心網友回復:
from sys import stdin, stdout
res = ''
while True:
line = stdin.readline()
if line:
res = line #do calculations
else:
break
stdout.write(res)
或使用 python 3.8 中的海象運算子:
while True:
if line := stdin.readline():
pass # do calculations with line
else:
break
這將繼續從標準輸入獲取值,直到ctrl d被按下
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/426450.html
