Post

PythonPython

L
Lakshmi sowjanya

Posted on 20th April 2024|26 views

0
votes

Read From Stdin Python

How to read from stdin in Python?

Answers
P
Surya kumar

Posted on 20th April 2024

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")

 

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos