Posted on 10th September 2024|26 views
How to read from stdin in Python?
Posted on 10th September 2024| views
There are three ways to read stdin in python I will explain each of them with an example:
1. sys.stdin:
import sys
for line in sys.stdin:
if 'Exit' == line.rstrip():
break
print(f'Processing the Message of sys.stdin ***{line}***')
print("completed")
2. Using input() function to read stdin data:
while True:
data = input("enter your message:\n")
if 'Exit' == data:
break
print(f'Processing the Message of input() ***{data}***')
print("completed")
3. Reading the standard input by using fileinput module:
import fileinput
for fileinput_line in fileinput.input():
if 'Exit' == fileinput_line.rstrip():
break
print(f'Processing the Message of fileinput.input() ***{fileinput_line}***')
print("completed")