Skip to content
Related Articles

Related Articles

Take input from stdin in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 01 Jul, 2022

In this article, we will see How to Read from stdin in Python

There are a number of ways in which we can take input from stdin in Python

Method 1: Read Input From stdin in Python using sys.stdin

The sys module in python helps us to access the variables maintained by the interpreter. It also provides functions to interact with the interpreter. To use sys in Python, we firstly import sys

Using sys.stdin: sys.stdin can be used to get input from the command line directly. It used is for standard input. It internally calls the input() method. It, also, automatically adds ‘\n’ after each sentence. let see a sys stdin python example:


import sys
for line in sys.stdin:
    if 'q' == line.rstrip():
    print(f'Input : {line}')



Method 2:Read Input From stdin in Python using input()

The input() can be used to take input from the user while executing the program and also in the middle of the execution.


# this accepts the user's input
# and stores in inp
inp = input("Type anything")
# prints inp



Method 3: Read Input From stdin in Python using fileinput.input()

Using fileinput.input(): If we want to read more than one file at a time, we use fileinput.input() . There are two ways to use fileinput.input(). To use this method, first, we need to import fileinput.

Example 1: 

Here, we pass the name of the files as a tuple in the “files” argument. Then we loop over each file to read it.


import fileinput
with fileinput.input(files=('sample.txt', 'no.txt')) as f:
    for line in f:



Example 2: 

Here, we pass the file name a sys argument in the command line. 


import fileinput
for f in fileinput.input():



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!