python/cpython · error
lost sys.stderr\n
Error message
lost sys.stderr\n
What it means
stderr trace from CPython's warnings machinery: while trying to print a warning ('filename:lineno: Category: text'), sys.stderr could not be fetched (PySys_GetOptionalAttr returned <= 0, i.e. missing or erroring). The fallback note 'lost sys.stderr' is printed to the real C stderr and the warning display aborts.
Source
Thrown at Python/_warnings.c:661
}
static void
show_warning(PyThreadState *tstate, PyObject *filename, int lineno,
PyObject *text, PyObject *category, PyObject *sourceline)
{
PyObject *f_stderr = NULL;
PyObject *name;
char lineno_str[128];
PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
name = PyObject_GetAttr(category, &_Py_ID(__name__));
if (name == NULL) {
goto error;
}
if (PySys_GetOptionalAttr(&_Py_ID(stderr), &f_stderr) <= 0) {
fprintf(stderr, "lost sys.stderr\n");
goto error;
}
/* Print "filename:lineno: category: text\n" */
if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
goto error;
if (PyFile_WriteString(lineno_str, f_stderr) < 0)
goto error;
if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
goto error;
if (PyFile_WriteString(": ", f_stderr) < 0)
goto error;
if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
goto error;
if (PyFile_WriteString("\n", f_stderr) < 0)
goto error;
Py_CLEAR(name);
View on GitHub (pinned to bc6749cc3b)
Solutions
- Do not delete sys.stderr; replace it with a real file or io object (e.g. open(os.devnull, 'w')) instead
- In embedded interpreters, keep sys streams valid for the whole interpreter lifetime
- Suppress unwanted warnings via warnings.filterwarnings or the -W option rather than removing stderr
- Ensure daemon/late callbacks that can warn run before interpreter finalization tears down sys
Example fix
# before
import sys
del sys.stderr # later warnings print 'lost sys.stderr'
# after
import sys, os
sys.stderr = open(os.devnull, 'w')
# or better: warnings.filterwarnings('ignore', category=DeprecationWarning) Defensive patterns
Strategy: fallback
Validate before calling
import sys, os
def ensure_stderr():
"""Guarantee sys.stderr is a usable stream before code that can warn."""
if not hasattr(sys, 'stderr') or sys.stderr is None or sys.stderr.closed:
sys.stderr = open(os.devnull, 'w') Type guard
import sys
def stderr_ok() -> bool:
"""True if sys.stderr exists and accepts writes."""
s = getattr(sys, 'stderr', None)
try:
return s is not None and not s.closed
except Exception:
return False Try / catch
# warnings display is C-level; guard at setup time instead
def install_quiet_stderr():
import sys, os, warnings
sys.stderr = open(os.devnull, 'w') # keep a VALID stream
warnings.filterwarnings('ignore') # plus filter, never del sys.stderr Prevention
- Never `del sys.stderr` — replace it with an open devnull file if silencing is needed
- Use warnings.filterwarnings or -W flags rather than removing streams
- In embedded interpreters, initialize and keep sys streams until Py_Finalize
- Trigger late warnings (e.g. from __del__) before shutdown begins
When it happens
Trigger: Interpreter/embedding environments where sys.stderr was deleted or replaced with an object whose attribute lookup fails; warnings emitted very late in interpreter shutdown after sys attributes are torn down; code doing `del sys.stderr` or assigning a broken object to it.
Common situations: Applications (GUI, services, test harnesses) that close or remove sys.stderr to silence output and then trigger warnings; embedded interpreters shutting down while a __del__ raises a warning; redirecting stderr to objects lacking file semantics.
Related errors
- warnings.showwarning() must be set to a function or method
- invalid action: {action!r}
- message must be a string
- category must be a Warning subclass
- module must be a string
AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14).
Data as JSON: /api/errors/f4358ad4e3b4dcd0.
Report an issue: GitHub.