Reading from stdin in Python

Introduction

In most programming languages, data can be read from various sources, like files, databases, or user input. However, one of the most common forms of input is the standard input, or stdin.

This article will provide a few different ways for reading from stdin in Python, which is an important skill for any developer working on command-line interfaces.

What is stdin?

Standard input, commonly referred to as stdin, is a stream from which a program reads its input data. It's one of the three standard streams in computer systems, alongside stdout (standard output) and stderr (standard error). By default, stdin refers to the data that a user inputs from the keyboard.

Note: The concept of stdin, stdout, and stderr comes from Unix-like operating systems, but it's also available in other systems like Windows. They are used for inter-process communication and can be redirected, which is a significant feature in shell scripting and system programming.

In Python, you can access stdin through the sys.stdin object, which behaves like a file object. This means you can use methods like read(), readline(), and readlines() to read from stdin, just as you would read from a file.

import sys

for line in sys.stdin:
    print(line)

In this simple example, the program will read from stdin line by line and print each line until it encounters an "EOF" (End of File) signal. You can send an EOF signal in the terminal by pressing Ctrl+D in Unix-like systems or Ctrl+Z in Windows.

Why read from stdin?

Standard input, or stdin, is a fundamental concept in computer programming that refers to the default data stream from which a program reads its input data. But why would you want to read from stdin instead of another source?

Well, reading from stdin is a common way to allow for dynamic user input during the program execution. It's also a way to receive data piped from another program. For example, let's say you have a program that processes text in some way, and you want to be able to use it in a Unix pipeline to process the output of another program. Reading from stdin is the way to go.

How to Read from stdin in Python

Python, like most programming languages, provides a few different ways to read from stdin. We'll explore a couple of the most common methods in the following sections.

Using sys.stdin

The sys.stdin object in Python is a file-like object that acts as the stdin stream for the Python program. You can read from this stream just like you would read from a file.

Here's an example:

import sys

line = sys.stdin.readline()

# Removing the trailing newline character
line = line.strip()

print(f"Received: {line}")

In this code, we simply use stdin's readline() method to get input from the user. The line is then printed out with the prefix "Received: ".

If you run this code and type in some input, you'll see that it echoes back each line you enter:

$ python read_stdin.py
Hello, world!
Received: Hello, world!

Using the input() Function

The input() function is a simpler way to read a line of input from stdin. This function reads a line of input, converts it to a string (stripping the trailing newline), and returns that string.

Here's an example:

line = input()
print("Received: " + line)

Again, if you run this code and type in some input, you'll see that it echoes back the line you enter:

$ python read_input.py
Hello, world!
Received: Hello, world!

The input() function always returns a string. If you want to read a number or some other type of data, you'll need to convert the string to that type using a function like int() or float().

Link: For more information on how to read and convert data to the correct formats, see the following articles:

Reading Multiple Lines from stdin

In Python, reading multiple lines from stdin can be accomplished in a couple of ways. One common approach is to use a for loop with sys.stdin. This allows you to iterate over each line that is entered until an EOF (End of File) character is received.

Here's an example:

import sys

for line in sys.stdin:
    print(line)

In this code, each line that is entered into stdin will be printed out. The program will continue to read lines until an EOF character is received. You can simulate this by pressing Ctrl+D in the terminal.

Another way to read multiple lines of input from stdin is by using the input() function inside a loop. This is a more user-friendly approach since it waits for the user to press Enter before reading the next line.

Here's how you can do it:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

while True:
    try:
        line = input()
        print(line)
    except EOFError:
        break

In this case, the program will also continue to read lines until an EOF character is received.

Note: The input() function automatically strips the newline character at the end of the line, while sys.stdin does not.

Reading Specific Number of Characters from stdin

Sometimes, you might want to read a specific number of characters from stdin. This can be done using the read() method provided by sys.stdin. The read() method takes an integer as an argument, which specifies the number of characters to read.

Here's an example where we read 10 characters from stdin:

import sys

chars = sys.stdin.read(10)
print(chars)

In this code, the program will read the first 10 characters of input and print them out. If less than 10 characters are entered, the program will wait for more input until it has read 10 characters. stdin has a read() function since it's a file-like object, thus, you can read only a given number of characters, just like you can with files.

Note: The read() method does not automatically strip newline characters, so if the input includes newline characters within the first 10 characters, they will be included in the output.

Remember, the input() function can also be used to read a specific number of characters, but it works slightly differently. The input() function reads a line of input (up to the newline character), and then you can use slicing to get the desired number of characters.

Here's an example:

line = input()
chars = line[:10]
print(chars)

In this case, the program will read a line of input, and then print the first 10 characters of that line. If the line is less than 10 characters long (not including the newline), the entire line will be printed.

Handling EOFError when Reading from stdin

While reading from stdin in Python, you might encounter an EOFError. This error is raised when one of the built-in functions like input() hits an end-of-file condition (EOF) without reading any data. This usually happens when you run a program that's expecting input but doesn't receive any. It's important to handle this error in your code to prevent your program from crashing unexpectedly.

Here's how you can gracefully handle an EOFError:

try:
    data = input()
except EOFError:
    print("EOFError encountered. No input received.")

In this code, we use a try-except block to catch and handle the EOFError. If input() hits an EOF condition, the program prints a message instead of crashing.

Conclusion

Reading from stdin is a fundamental task in Python programming, especially when dealing with command-line applications or scripts. In this article, we've explored what stdin is, why you might want to read from it, and how to do so using various methods. We've also covered how to handle an EOFError, which can occur when reading from stdin. Understanding these concepts will help you create more robust, reliable Python applications.

Last Updated: August 28th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms