You are currently viewing How do you read from stdin in Python?

One of the simplest methods to read from stdin is using the Python built-in input() function, which prompts the user to enter input from the keyboard and returns a string containing the input.

Advertisements

Standard input, or stdin for short, is a fundamental concept in computer programming. It allows programs to read input from the user or from other programs. In this article, we will explain how to read input from stdin in Python using the input() function and three other popular methods.

1. Quick Examples of Reading from Stdin in Python

These examples will give you a high-level idea of how to read input from the standard input stream in Python using four different methods. We will discuss these methods in detail.


import fileinput
import sys

# Using input() function
input_line = input("Enter text: ")

# Using sys.stdin
print("Enter text (type 'q' to quit): ")
for line in sys.stdin:
    line = line.rstrip()
    if line == "q":
        break

# Using fileinput.input()
print("Enter text (type 'q' to quit): ")
for line in fileinput.input():
    line = line.rstrip()
    if line == "q":
        break

# Using open(0).read()
print("Enter text (type 'q' to quit): ")
text = open(0).read().rstrip()
lines = text.split("\n")
for line in lines:
    if line == "q":
        break

2. Python input() Method to Read from stdin

This is the most common method to take input from stdin (standard input) in Python. The input() is a built-in function that allows you to read input from the user via stdin. When you call input(), python waits for the user to enter a line of text, and then returns the line as a string.

See the below example:


# Prompt on terminal asking for input
name = input("Enter your name: ")
print(f"Hello, {name}!")

The input() function always returns a string. So if you need to process the input as a different type (such as an integer or a floating-point number). You will need to use a type conversion function like int() or float().


age = input("Enter your age: ")
# The type of age will be string
print(type(age))
# We need to convert it to other types
age = int(age)

print(f"age: {age}!")

If you don’t provide a prompt string as an argument to input(), Python will still wait for the user to enter input, but there will be no visible prompt on the console.

3. Use sys.stdin to take Input from Stdin

The stdin is a variable in the sys module in Python that can be used to read from the console or stdin. It is a file-like object that represents the input stream of the interpreter. To use sys.stdin to read input from stdin, you can simply call the readline() method on it to read one line at a time

See the below example:


# Read input in Loop
import sys
for line in sys.stdin:
    print(line.strip())

This code will read input from stdin one line at a time and print each line to the console with whitespace stripped off the ends.

You can also use sys.stdin.read() to read all input at once as a string. See the example below:


# Read all at once
import sys
data = sys.stdin.read()
print(f"You entered {len(data)} characters")

sys.stdin is a file-like object, which means you can use all the methods and attributes of file objects on it. It includes like readline(), read(), close(), etc.

Unlike input(), sys.stdin does not automatically convert the input to a string, so you may need to call str() or bytes() to convert the input to the desired type.


import sys

# Read a single line of input from stdin
input_line = sys.stdin.readline()

# Convert the input to an integer
try:
    input_int = int(input_line)
except ValueError:
    print("Error: Input must be an integer")
    sys.exit(1)

# Perform some operation with the input integer
result = input_int * 2

# Output the result
print(result)

4. fileinput.input() – Input form Stdin

We have the fileinput module in Python, which is another alternative to read input from either stdin or one or more files specified as command-line arguments.


# Use loop and fileinput
import fileinput
for line in fileinput.input():
    print(line.strip())

5. open(0).read() – Read from Stdin

If you prefer a more concise way to read input from stdin in Python, you can use the open() function to create a file object that represents stdin, and then use the read() method to read all the input at once as a string.


input_str = open(0).read()
print(input_str)

The open(0) creates a file object that represents stdin (file descriptor 0), and calling read() on that object reads all the input at once.

This can be a convenient way to read input if you know it’s small enough to fit in memory. But it can be slower and less memory-efficient than using other methods like iterating over stdin line by line.

open(0) may not be available on all systems or platforms. So be sure to test your code thoroughly if you plan to use this method.

6. Summary and Conclusion

We have explained how to read from stdin in Python, Stdin is short for Standard Input. You have learned how to use input() function and other methods along that to read from stdin. I hope this article was helpful. Let me know if you have any questions.

Happy Coding!