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?

More than 1 year has passed since last update.

Pythonでfileか文字列を「標準入力へ」リダイレクトしstreamとして扱う

Last updated at Posted at 2023-03-22

こんにちは、tdzzです。

pythonの標準入力はstreamの特性を持ちます。データを取得しながら少しずつ処理することができます。しかし、入力ソースは時々ファイル・url形式で提供されて、データを取得するとき、同じコードを複数回書く場合があります。リダイレクト記号「<」を使ってもいいですが、ユーザー側で使い分けなければなりません。ですから、入力ソースを標準入力へリダイレクトして、標準入力を優雅に処理するコードを再利用しましょう。

やり方

リダイレクトしたいデータをStringIOBytesIOオブジェクトに変換し、with文でsys.stdinに代入すればよい。

import sys
from io import StringIO

s = """Carol
Yun Yan Cheng Yu
2021-11-02
"""

res = []
with StringIO(s) as sys.stdin:
    while True:
        line = sys.stdin.readline()
        if not line: break
        res.append(line)

print(res)
# 出力は ['Carol\n', 'Yun Yan Cheng Yu\n', '2021-11-02\n']

参照リンク

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?