{"record":{"id":"f4358ad4e3b4dcd0","repo":"python/cpython","slug":"lost-sys-stderr-n","errorCode":null,"errorMessage":"lost sys.stderr\\n","messagePattern":"lost sys\\.stderr\\\\n","errorType":"console","errorClass":null,"httpStatus":null,"severity":"error","filePath":"Python/_warnings.c","lineNumber":661,"sourceCode":"}\n\nstatic void\nshow_warning(PyThreadState *tstate, PyObject *filename, int lineno,\n             PyObject *text, PyObject *category, PyObject *sourceline)\n{\n    PyObject *f_stderr = NULL;\n    PyObject *name;\n    char lineno_str[128];\n\n    PyOS_snprintf(lineno_str, sizeof(lineno_str), \":%d: \", lineno);\n\n    name = PyObject_GetAttr(category, &_Py_ID(__name__));\n    if (name == NULL) {\n        goto error;\n    }\n\n    if (PySys_GetOptionalAttr(&_Py_ID(stderr), &f_stderr) <= 0) {\n        fprintf(stderr, \"lost sys.stderr\\n\");\n        goto error;\n    }\n\n    /* Print \"filename:lineno: category: text\\n\" */\n    if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)\n        goto error;\n    if (PyFile_WriteString(lineno_str, f_stderr) < 0)\n        goto error;\n    if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)\n        goto error;\n    if (PyFile_WriteString(\": \", f_stderr) < 0)\n        goto error;\n    if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)\n        goto error;\n    if (PyFile_WriteString(\"\\n\", f_stderr) < 0)\n        goto error;\n    Py_CLEAR(name);\n","sourceCodeStart":643,"sourceCodeEnd":679,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Python/_warnings.c#L643-L679","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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"],"exampleFix":"# before\nimport sys\ndel sys.stderr            # later warnings print 'lost sys.stderr'\n\n# after\nimport sys, os\nsys.stderr = open(os.devnull, 'w')\n# or better: warnings.filterwarnings('ignore', category=DeprecationWarning)","handlingStrategy":"fallback","validationCode":"import sys, os\n\ndef ensure_stderr():\n    \"\"\"Guarantee sys.stderr is a usable stream before code that can warn.\"\"\"\n    if not hasattr(sys, 'stderr') or sys.stderr is None or sys.stderr.closed:\n        sys.stderr = open(os.devnull, 'w')","typeGuard":"import sys\n\ndef stderr_ok() -> bool:\n    \"\"\"True if sys.stderr exists and accepts writes.\"\"\"\n    s = getattr(sys, 'stderr', None)\n    try:\n        return s is not None and not s.closed\n    except Exception:\n        return False","tryCatchPattern":"# warnings display is C-level; guard at setup time instead\ndef install_quiet_stderr():\n    import sys, os, warnings\n    sys.stderr = open(os.devnull, 'w')          # keep a VALID stream\n    warnings.filterwarnings('ignore')           # plus filter, never del sys.stderr","preventionTips":["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"],"tags":["warnings","sys-stderr","interpreter-shutdown","embedding"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}