Sometimes you may need to read input from stdin in Python. In this article, we will learn some of the easy ways to do this. This is not a typical software requirement but may come up in programming contests and interviews. So it is good to know.
How to Read from Stdin in Python
Here are the different ways to read from stdin in Python.
1. Using sys.stdin
One of the simplest ways to read from stdin is using sys.stdin
import sys for line in sys.stdin: print(line)
The above code, when run, will keep accepting input from stdin and printing it immediately. It will also include newline character. If you don’t want to include newline character, you can use rstrip() function as shown below.
import sys for line in sys.stdin: print(line.rstrip())
2. Using fileinput
You can also use fileinput module for this purpose.
import fileinput for line in fileinput.input(): pass
When you run the above script, the above code will loop through all lines in input, specified as file names, given as command line argument, or standard input if no argument is given.
The main difference between these above functions and input() function in python is that the above functions allow you to read multiple lines or file contents, whereas input() function allows you to read only one line.
In this article, we have learnt a couple of simple ways to read from standard input in Python.