Python Stdin, Stdout, and Stderr

When I was working on a Python script that needed to take input from the command line, display results to the user, and log errors separately.

The issue was… I realized many beginners (and even some experienced developers) are not fully aware of how stdin, stdout, and stderr work in Python.

So, in this tutorial, I’ll share everything I’ve learned about these three streams in my Python development journey. I’ll also cover multiple methods with practical examples so you can start using them right away.

What are stdin, stdout, and stderr in Python?

  • stdin (Standard Input): This is where Python reads input from. By default, it’s your keyboard.
  • stdout (Standard Output): This is where Python sends normal output. By default, it’s your terminal screen.
  • stderr (Standard Error): This is where Python sends error messages. By default, it also goes to your screen, but it can be redirected separately.

Think of them as three communication channels between your Python program and the outside world.

Method 1 – Use input() and print() (Default Behavior)

The simplest way to use stdin and stdout is through the input() and print() methods in Python.

Here’s an example:

# Example 1: Using stdin and stdout
name = input("Enter your name: ")   # Reads from stdin (keyboard)
print(f"Hello, {name}! Welcome to Python.")   # Writes to stdout (screen)

I executed the above example code and added the screenshot below.

python print to stderr

When I run this script, Python waits for me to type something. Once I press Enter, it prints the greeting.

Method 2 – Use sys.stdin, sys.stdout, and sys.stderr

For more control, Python provides sys.stdin, sys.stdout, and sys.stderr as file-like objects.

Here’s how I use them:

import sys

# Example 2: Reading and writing with sys.stdin, sys.stdout, sys.stderr
sys.stdout.write("Enter your favorite city in the USA: ")
city = sys.stdin.readline().strip()   # Reads input directly
sys.stdout.write(f"You entered: {city}\n")

# Simulating an error
if city.lower() not in ["new york", "los angeles", "chicago", "houston"]:
    sys.stderr.write("Warning: That city is not in the top 4 by population.\n")

I executed the above example code and added the screenshot below.

stdout python

This approach is useful when I need to redirect input/output to files or when I want to separate errors from normal output.

Method 3 – Redirect stdout and stderr to a File

Sometimes, I don’t want the output on the screen. For example, when I run a script overnight on a server, I prefer saving logs to a file.

Here’s how I redirect stdout and stderr:

import sys

# Example 3: Redirecting stdout and stderr
with open("output.log", "w") as f_out, open("error.log", "w") as f_err:
    sys.stdout = f_out
    sys.stderr = f_err

    print("This will go to output.log")
    raise ValueError("This error will go to error.log")

I executed the above example code and added the screenshot below.

python print stderr

When I run this, the normal message goes to output.log, and the error goes to error.log.

Method 4 – Use Subprocess with stdin, stdout, and stderr

In real-world applications, I often need to run external commands (like shell commands) from Python. In such cases, the subprocess module is my go-to.

Here’s an example:

import subprocess

# Example 4: Using subprocess with stdin, stdout, and stderr
process = subprocess.Popen(
    ["python", "-c", "print('Hello from subprocess!'); raise ValueError('Oops!')"],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
)

out, err = process.communicate()

print("Captured stdout:", out)
print("Captured stderr:", err)

I executed the above example code and added the screenshot below.

stdin and stdout in python

This lets me capture both stdout and stderr from another program and handle them separately in Python.

Method 5 – Print to stderr Directly

Sometimes, I want to show an error message without raising an exception. In such cases, I print directly to stderr.

import sys

# Example 5: Printing error messages to stderr
print("Processing data...", file=sys.stdout)
print("Error: Invalid data format!", file=sys.stderr)

This way, the error message doesn’t get mixed with normal output.

Method 6 – Redirect Streams Temporarily

Another trick I use is redirecting stdout temporarily, especially when I want to capture printed output inside my code.

import sys
import io

# Example 6: Temporarily redirecting stdout
buffer = io.StringIO()
sys_stdout_backup = sys.stdout
sys.stdout = buffer

print("This will be captured instead of printed.")

sys.stdout = sys_stdout_backup  # Restore stdout
captured_output = buffer.getvalue()

print("Captured text:", captured_output)

This is super handy for testing when I want to check what my function prints without actually displaying it on the screen.

So, that’s how I use stdin, stdout, and stderr in Python.

  • For simple scripts, input() and print() are enough.
  • For advanced control, sys.stdin, sys.stdout, and sys.stderr give me flexibility.
  • For automation and logging, I often redirect streams to files.
  • For running external commands, subprocess is my best friend.

Both beginners and experienced developers can benefit from mastering these three streams. They’re the foundation of how Python communicates with the outside world.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.