Take input from stdin in Python
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
There are a number of ways in which we can take input from stdin in Python.
- 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.
- Using input(): input() can be used to take input from the user while executing the program and also in the middle of the execution.
- Using fileinput.input(): If we want to read more that 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.
1st method :
Here, we pass the name of the files as a tuple in the “files” argument. Then we loop over each file to read it.
- 2nd method :
Here, we pass the file name a sys argument in the command line.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course