Write errors to stderr

Easysys Module Programs · 6 of 20

Write a Python program that writes normal output to stdout and errors to stderr.

Advertisement
Output
stdout: report ready
stderr: warning: 2 tests skipped

Approach

  1. print(..., file=sys.stderr); run it and capture both streams separately.

Solution

Python
import subprocessimport sys code = "import sys\nprint('report ready')\nprint('warning: 2 tests skipped', file=sys.stderr)"r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)print("stdout:", r.stdout.strip())print("stderr:", r.stderr.strip())
Output
stdout: report ready
stderr: warning: 2 tests skipped

Learn the concept

New to this topic? Read the lesson, then come back.

More sys module programs

← All 20 sys Module Programs

Leave a Comment