{"record":{"id":"8fd71fbde7a8678a","repo":"python/cpython","slug":"lost-sys-stderr-n-8fd71f","errorCode":null,"errorMessage":"lost sys.stderr\\n","messagePattern":"lost sys\\.stderr\\\\n","errorType":"console","errorClass":null,"httpStatus":null,"severity":"error","filePath":"Python/pythonrun.c","lineNumber":1197,"sourceCode":"         PyErr_FormatUnraisable(\n             \"Exception ignored in the internal traceback machinery\");\n     }\n#endif\n    PyErr_Clear();\n    struct exception_print_context ctx;\n    ctx.file = file;\n\n    /* We choose to ignore seen being possibly NULL, and report\n       at least the main exception (it could be a MemoryError).\n    */\n    ctx.seen = PySet_New(NULL);\n    if (ctx.seen == NULL) {\n        PyErr_Clear();\n    }\n    if (print_exception_recursive(&ctx, value) < 0) {\n        PyErr_Clear();\n        PyObject_Dump(value);\n        fprintf(stderr, \"lost sys.stderr\\n\");\n    }\n    Py_XDECREF(ctx.seen);\n\n    /* Call file.flush() */\n    if (_PyFile_Flush(file) < 0) {\n        /* Silently ignore file.flush() error */\n        PyErr_Clear();\n    }\n}\n\nvoid\nPyErr_Display(PyObject *unused, PyObject *value, PyObject *tb)\n{\n    PyObject *file;\n    if (PySys_GetOptionalAttr(&_Py_ID(stderr), &file) < 0) {\n        PyObject *exc = PyErr_GetRaisedException();\n        PyObject_Dump(value);\n        fprintf(stderr, \"lost sys.stderr\\n\");","sourceCodeStart":1179,"sourceCodeEnd":1215,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Python/pythonrun.c#L1179-L1215","documentation":"Printed by _PyErr_Display (Python/pythonrun.c) after print_exception_recursive fails and the fallback PyObject_Dump(value) is used. 'lost sys.stderr' means the exception could not be formatted and written to the error file through the normal machinery — typically because writing to sys.stderr itself raised (closed pipe, custom sys.stderr whose write failed) or unrecoverable MemoryError during formatting. The original exception is dumped in raw object form instead of a readable traceback.","triggerScenarios":"sys.stderr replaced by an object whose write/flush raises while an unhandled exception is being printed; sys.stderr attached to a closed pipe (e.g. python | head closing early); MemoryError while formatting a huge exception chain.","commonSituations":"`python script.py | head` where head exits first (SIGPIPE/EPIPE); user code or sitecustomize swapping sys.stderr for a broken wrapper; deeply recursive exception chains exhausting memory during display.","solutions":["If piping output, consume it fully or handle EPIPE: use `python script.py | head || true`, or trap SIGPIPE","Restore/repair sys.stderr before the failure point; wrap custom stderr objects so write() never raises","For MemoryError-driven cases, reduce recursion/exception-chain depth or raise memory limits"],"exampleFix":"# before\nclass BadStderr:\n    def write(self, s): raise OSError('broken')\nsys.stderr = BadStderr()\nraise ValueError('boom')\n# after\nclass SafeStderr:\n    def write(self, s):\n        try: return sys.__stderr__.write(s)\n        except Exception: return 0\nsys.stderr = SafeStderr()\nraise ValueError('boom')","handlingStrategy":"fallback","validationCode":"# make custom stderr writes non-raising before user code runs\nimport sys\nclass SafeStderr:\n    def write(self, s):\n        try:\n            sys.__stderr__.write(s)\n        except Exception:\n            pass\n        return len(s)\n    def flush(self): pass\nsys.stderr = SafeStderr()","typeGuard":null,"tryCatchPattern":"# treat output loss as a signal, not a crash: check pipe status\n# bash\nset -o pipefail\npython app.py | head || echo \"output pipe closed early\" >&2","preventionTips":["When piping python output into head/tail, expect EPIPE and handle it (|| true, SIGPIPE trap)","Any sys.stderr replacement must swallow write/flush errors itself","Avoid gigantic exception chains in memory-tight processes; they can fail during display"],"tags":["cpython","stderr","unhandled-exception","epipe","display"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}