0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

改行が3連続で入力されるまで入力を受け付けるスクリプト

Posted at
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}")

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?