Introduction
In this article, we will explore how to take input from standard input (stdin) in Python. There are several ways to accomplish this:
- Using
sys.stdin - Using
input() - Using
fileinput.input()
Read Input from stdin in Python using sys.stdin
First, we need to import the sys module. sys.stdin can be used to get input directly from the command line. It is useful for reading standard input and automatically adds a newline after each line.
import sys
for line in sys.stdin:
if 'exit' == line.rstrip():
break
print(f'You entered: {line.strip()}')
print("Exiting the program.")
Output:
Type your input here (type 'exit' to quit): Hello You entered: Hello Goodbye You entered: Goodbye Exiting the program.
Read Input from stdin in Python using input()
The input() function can be used to take input from the user during program execution.
# Prompt user for input
user_input = input("What is your favorite book? ")
# Display the user's input
print("You said:", user_input)
Output:
What is your favorite book? The Great Gatsby You said: The Great Gatsby
Read Input from stdin in Python using fileinput.input()
If we want to read multiple files at once, we can use fileinput.input(). First, we need to import the fileinput module.
Example 1: Reading Multiple Files by Providing File Names
In this example, we pass the names of the files as a tuple to the fileinput.input() function:
import fileinput
with fileinput.input(files=('file1.txt', 'file2.txt')) as f:
for line in f:
print(line.strip())
Output:
(Contents of file1.txt and file2.txt will be printed line by line)
Example 2: Reading Multiple Files from Command Line
Here, we pass file names as positional arguments from the command line:
import fileinput
for line in fileinput.input():
print(line.strip())
Output:
(Contents of specified files will be printed line by line)
Conclusion
Taking input from stdin in Python provides flexibility in handling user input and reading data from files. By utilizing modules like sys and fileinput, you can enhance the interactivity of your applications, making it easier to gather data from various sources.

0 Comments