Python Practice › sys Module Programs › Program 6
Write errors to stderr
Write a Python program that writes normal output to stdout and errors to stderr.
Output
stdout: report ready stderr: warning: 2 tests skipped
Approach
print(..., file=sys.stderr); run it and capture both streams separately.
Solution
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.