Python read all lines from stdin


Tags: python
Reading time: less than 1 minute

Question

How to read all lines from standard input in Python? How can I read the standard input line by line?

Answer

In Python, the standard input is exposed as sys.stdin.. As sys.stdin is a file, the lines can be iterated just like any other file in Python.

import sys

for line in sys.stdin:
    print(line)

It is also possible to read the lines as bytes instead of a Unicode str. To do that, you can use the .buffer property of the input stream.

import sys

for line in sys.stdin.buffer:
    print(line)

Citation

If you find this work useful, please cite it as:
@article{yaltirakliqnapythonreadlinesstdin,
  title   = "Python read all lines from stdin",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2024",
  url     = "https://www.gkbrk.com/qna/python-read-lines-stdin/"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "Python read all lines from stdin", December, 2024. [Online]. Available: https://www.gkbrk.com/qna/python-read-lines-stdin/. [Accessed Dec. 17, 2024].
APA Style
Yaltirakli, G. (2024, December 17). Python read all lines from stdin. https://www.gkbrk.com/qna/python-read-lines-stdin/
Bluebook Style
Gokberk Yaltirakli, Python read all lines from stdin, GKBRK.COM (Dec. 17, 2024), https://www.gkbrk.com/qna/python-read-lines-stdin/

Comments

© 2024 Gokberk Yaltirakli