Read from Stdin in Python

Rate this post

Problem Statement: Reading from stdin in Python.

Reading inputs from the user is one of the fundamental building blocks that we learn while learning any programming language. The output of most codes depends on the user’s inputs. Hence, in this article, we are going to learn how to read from stdin in Python.

There are numerous ways to accept the user input in Python. We can either read from the console directly or we can also read from a file specified in the console. Confused? Don’t worry, we got you covered. So, without further delay let’s begin our mission and let’s have a look at the various approaches to read the input from stdin in Python.

Method 1: Using sys.stdin

One way to read from stdin in Python is to use sys.stdin. The sys.stdin gets input from the command line directly and then calls the input() function internally. It also adds a newline ‘\n’ character automatically after taking the input. To remove this newline character you can simply eliminate it using the rstrip() built-in function of Python.

Note: Ensure to import the sys module in your code before utilizing sys.stdin.

Example: In the following snippet, we will use a loop along with sys.stdin that will keep accepting the input from the user till the user wants to terminate the script.

# Importing the sys module
import sys

print("Enter the input.\n NOTE: To stop execution please enter 'quit'")
# Program terminates as soon as user enters 'quit'
for line in sys.stdin:
    if 'quit' == line.rstrip():
        break
    print(f'User Input : {line}')

print("Terminated!")

Output:

Enter the input.
 NOTE: To stop execution please enter 'quit'
Hello! Welcome to Finxter! 
User Input : Hello! Welcome to Finxter! 

quit
Terminated!

Method 2: Using Python’s Built-In input() function

Python’s built-in input() function reads a string from the standard input. The function blocks until such input becomes available and the user hits ENTER. You can add an optional prompt string as an argument to print a custom string to the standard output without a trailing newline character to tell the user that your program expects their input.

Example 1:

# Reading the input from the user
i = input("Enter anything: ")
print("The Input is: ", i)

Output:

Enter anything: Welcome Finxter
The Input is:  Welcome Finxter

Example 2: Following is another example that reads and processes the input message in the until the user enters the correct input that meets the condition.

Example:

while True:
    # Reading the input from the user
    i = input("What is the value of 2 + 8")
    # Only exits when meets the condition
    if i == '10':
        break
    print("The value", i, "is the wrong answer. Try again")
print("The value", i, "is the right answer")

Suppose the value insert first is 7 followed by 10. The output will be as follows:

Output:

What is the value of 2 + 8 7
7
The value 7 is the wrong answer. Try again
What is the value of 2 + 8 10
10
The value 10 is the right answer

Related Video

Method 3: Using The fileinput Module

We can also utilize Python’s fileinput module to read from standard input. The fileinput.input() method is used to read through all the lines in the input filenames specified in command-line arguments. If no argument value is given, it takes the input from the terminal and if the argument value is given as the name of an existing file, it will take the input from that file.

Note: This fileinput.input() method is similar to sys.stdin and it also adds a newline character (\n) to the end of the input data.

Example 1: Let’s look at an example where we can get the data of the file line by line by using fileinput.input() method.

# Importing the fileinput module
import fileinput

print("Enter anything:\n[If you enter 'END' the program will terminate]")
# Reading the input from the user
for line in fileinput.input():
    if line.strip() == "end".lower():
        break
    print("The input value entered is:", line)
    print("Enter anything:")
print("End of file")

Output:

Enter anything:
[If you enter 'END' the program will terminate]
Hello and Welcome to Finxter!
The input value entered is: Hello and Welcome to Finxter!

Enter anything:
End
End of file

Example 2: In the following example, Python will accept data from a file instead of the terminal. Let’s consider that we have the following text file (filename- “demo.txt”) as shown below –

# Importing the fileinput module
import fileinput
# You have to feed in the filename as the argument value of the fileinput.input() function. 
for line in fileinput.input(files = 'demo.txt'):
    print(line)

Output:

This is line 1.
Hello and Welcome to Finxter!
input()sys.stdin.readline()
input() strips off any newline from the end of the input. Hence, it’s faster to use if you want to strip off the line.We have to use sys.stdin.readline().strip() to strip off any newline from the end of the input.
Input() will raise an EOFError when called if there is no more input.On the other hand, sys.stdin.readline will return an empty string at EOF.
Reading large amounts of data input() is much slower.Reading large amounts of data sys.stdin.readline() is faster.
  • Example:
import sys

# sys.stdin.readline()
for i in range(int(sys.argv[1])):
    sys.stdin.readline()
# It takes 0.25μs per iteration.

# inut()
for i in range(int(sys.argv[1])):
	input()
#It is 10 times slower than the sys.readline().

Conclusion

In this tutorial, we looked at three different methods to read from stdin in Python:

  • input(),
  • sys.stdin,
  • and the fileinput.input().

I hope this article has helped to answer your queries. Please subscribe and stay tuned for more interesting articles in the future.


Finxter Computer Science Academy

  • One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
  • So, do you want to master the art of web scraping using Python’s BeautifulSoup?
  • If the answer is yes – this course will take you from beginner to expert in Web Scraping.