Python – stdin stdout and stderr [6 Examples]

In this Python tutorial, I will explain what Python – stdin stdout and stderr mean and will also see some examples related to this.

Understanding input and output streams is good for communication between a program and the environment.

Python offers streams that serve as representations of stdin, stdout, and stderr. Let’s explore how we can utilize these objects to manage the input, output, and error of our program.

What are Python – stdin stdout and stderr in file handling?

Standard input: It is commonly referred to as stdin in Python and serves as the file handle through which a user program retrieves information from the user. Input is provided to the program via the standard input in Python.

Standard output: It is also known as stdout in Python, where the user program writes regular information. Output is conveyed through the standard output in Python, allowing the program to display information to the user.

Standard error: This is denoted as stderr in Python and is utilized by the user program for writing error information. Errors are communicated through the standard error, facilitating the identification and handling of errors separately from regular program output in Python.

stdin in Python

The Python stdin represents the standard input stream, typically associated with data coming into the program. This stream is where the program receives input from various sources, such as the keyboard or another program’s output.

In Python, we can read input from stdin using the input() function or by reading from the sys.stdin object.

Here’s a simple example:

name = input("Enter your name: ")
print("Hello, " + name + "!")
print("Welcome to PythonGuides!")

Output:

Enter your name: Chandler M Bing
Hello, Chandler M Bing!
Welcome to PythonGuides!

The output can be seen in the screenshot below after executing the code in PyCharm.

Python – stdin stdout and stderr

Python sys.stdin class

Let’s see an example where we will use the sys.stdin class in Python.

import sys

print("Enter your favorite city in the United States (type 'exit' to quit):")

for line in sys.stdin:
    city = line.strip()
    if city.lower() == 'exit':
        print('Exiting the program...')
        exit(0)
    else:
        print('Your favorite city in the United States is:', city)

Output: Within the for loop, we iterate over the input from the stdin in Python until it is open.

If the string after removing the newline characters using the strip() function from the back equals the “exit” string, then the program will exit using exit(0). Else, the program will print the input data.

Enter your favorite city in the United States (type 'exit' to quit):
new york
Your favorite city in the United States is: new york
texas
Your favorite city in the United States is: texas
exit
Exiting the program...

The screenshot below shows the code implemented in the PyCharm editor.

stdin and stdout in python

stdout in Python

The Python stdout represents the standard output stream, where a program writes its regular output. This stream is used for displaying information, results, or any other output generated by the program.

By default, the print() function in Python writes to stdout, making it the primary method for producing output in Python programs.

Consider the following example:

print("Hello and Welcome to PythonGuides")

Output: The string is printed to the standard output in Python, typically the console or terminal where the program is executed.

Hello and Welcome to PythonGuides

Below is the screenshot mentioned after implementing the code in the Pycharm editor.

python stdout

Python sys.stdout class

Here is an example of using the sys.stdout class in Python:

import sys

stdout_fileno = sys.stdout
sample_input = [
    "Welcome to the United States!",
    "Explore the Statue of Liberty in New York City",
    "Visit the Grand Canyon in Arizona",
    "Experience the magic of Disneyland in California"
]
for message in sample_input:
    stdout_fileno.write(message + '\n')

Output: Here, we are just iterating over the input data and writing the data as an output using sys.stdout in Python.

Welcome to the United States!
Explore the Statue of Liberty in New York City
Visit the Grand Canyon in Arizona
Experience the magic of Disneyland in California

Upon executing the code in PyCharm, the output can be viewed in the screenshot below.

python stdin stdout

stderr in Python

The Python stderr represents the standard error stream, which is used for displaying error messages and diagnostic information.

Unlike stdout in Python, stderr is typically not buffered, meaning that error messages appear immediately on the screen, even if stdout is redirected or piped. In Python, error messages and exceptions are automatically directed to stderr.

For instance:

import sys

try:
    result = 10 / 0
except Exception as e:
    print("An error occurred:", str(e), file=sys.stderr)

Output:

An error occurred: division by zero

Refer to the screenshot below for the code implementation in the PyCharm editor.

python print stderr

Python sys.stderr class

Here is an instance to check how to use sys.stderr class in Python:

import sys

stdout_fileno = sys.stdout
stderr_fileno = sys.stderr
sample_input = ['New York', 'Los Angeles', 'Chicago', 'exit']
for input_data in sample_input:
    stdout_fileno.write(f"Processing: {input_data}\n")
    try:
        result = input_data + 100
    except Exception as e:
        stderr_fileno.write(f"Error processing '{input_data}': {str(e)}\n")

Output: We are iterating over our input data using a for loop in Python. and we are using our try and except blocks.
In the try block, we are trying to perform an operation that may raise an exception, and in the except block, we are catching the error and printing the error message through stderr in Python.

Processing: New York
Processing: Los Angeles
Processing: Chicago
Processing: exit
Error processing 'New York': can only concatenate str (not "int") to str
Error processing 'Los Angeles': can only concatenate str (not "int") to str
Error processing 'Chicago': can only concatenate str (not "int") to str
Error processing 'exit': can only concatenate str (not "int") to str

After implementing the code in the PyCharm editor, refer to the screenshot below.

stdin stdout stderr in python

Conclusion

After reading this, we came to know what Python – stdin stdout and stderr are in detail. They are essential components of the standard I/O system for input, output, and error handling in Python Programming.

Understanding how Python stdin, stdout, and stderr streams will help enhance our Python application’s functionality.

I have also explained how to use these in Python file handling.

You may also like to read: