import sys
def read_input_until_three_newlines():
"""
標準入力から複数行を受け付け、改行が3連続で入力された場合に確定する。
最後の改行2つはリストから削除して返す。
"""
lines = []
empty_line_count = 0
print("複数行の入力を開始します。改行を3回連続で入力すると確定します(Ctrl+Dで終了)。")
while True:
try:
# 1行入力を取得
line = sys.stdin.readline()
if line == "": # EOF(Ctrl+D)
print("入力を終了します。")
break
line = line.rstrip("\r\n") # 改行を削除
if line == "":
empty_line_count += 1
if empty_line_count >= 2:
# 改行3連続で入力終了
print("確定します。")
break
else:
empty_line_count = 0 # リセット
lines.append(line)
except KeyboardInterrupt:
print("\nキャンセルされました。")
return []
# 最後の2つの改行を削除
while lines and lines[-1] == "":
lines.pop()
return lines
if __name__ == "__main__":
while True:
result = read_input_until_three_newlines()
print("\n取得された行:")
for idx, line in enumerate(result, start=1):
print(f"{idx}: {line}")
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme