1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

標準入力をコード中に記述する

Last updated at Posted at 2020-06-09

例えば標準入力のテストをしたい時など、毎回入力するのも面倒だし、かといって外部ファイル読み込むのもゴミが増えるだけ
なるべく元のコードを汚さずにテストしたい場合、input()をオーバーライドするのがよさそう

以下のようにテストしたい標準入力の中身を書いておいて、

stdin_test = """1 2
3 4
5 6
"""

ジェネレータでinput()をオーバーライドする

def inp(t):
    from io import StringIO
    for i in StringIO(t):
        yield i
input = inp(stdin_test).__next__

使用例

a = [list(map(int, input().split())) for i in range(3)]
print(a)

>>> [[1, 2], [3, 4], [5, 6]]

もっといいやり方がある気がしないでもない
おわり

1
3
3

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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?