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", November, 2024. [Online]. Available: https://www.gkbrk.com/qna/python-read-lines-stdin/. [Accessed Nov. 12, 2024].
APA Style Yaltirakli, G. (2024, November 12). 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 (Nov. 12, 2024), https://www.gkbrk.com/qna/python-read-lines-stdin/