How to Read from stdin in Python With Examples

There are three ways to read data from stdin in Python.

  1. sys.stdin
  2. input() built-in function
  3. fileinput.input() function

1. Using sys.stdin to read from standard input

Python sys module stdin is used by the interpreter for standard input. Internally, it calls the input() function. The input string is appended with a newline character (n) in the end. So, you can use the rstrip() function to remove it.

Here is a simple program to read user messages from the standard input and process it. The program will terminate when the user enters “Exit” message.

import sys
for line in sys.stdin:
    if 'Exit' == line.rstrip():
    print(f'Processing Message from sys.stdin *****{line}*****')


Processing Message from sys.stdin *****Hi
Processing Message from sys.stdin *****Hello
Python stdin Example


Python stdin Example

Notice the use of rstrip() to remove the trailing newline character so that we can check if the user has entered “Exit” message or not.

2. Using input() function to read stdin data

We can also use Python input() function to read the standard input data. We can also prompt a message to the user.

Here is a simple example to read and process the standard input message in the infinite loop, unless the user enters the Exit message.

while True:
    data = input("Please enter the message:n")
    if 'Exit' == data:
    print(f'Processing Message from input() *****{data}*****')


Python fileinput.input() Read Standard Input


Python input() Read From stdin

The input() function doesn’t append newline character to the user message.

3. Reading Standard Input using fileinput module

We can also use fileinput.input() function to read from the standard input. The fileinput module provides utility functions to loop over standard input or a list of files. When we don’t provide any argument to the input() function, it reads arguments from the standard input.

This function works in the same way as sys.stdin and adds a newline character to the end of the user-entered data.

import fileinput
for fileinput_line in fileinput.input():
    if 'Exit' == fileinput_line.rstrip():
    print(f'Processing Message from fileinput.input() *****{fileinput_line}*****')


Python fileinput.input() Read Standard Input

Python fileinput.input() Read Standard Input

By admin

Leave a Reply

%d bloggers like this: