| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
Duplicate stdin/stdout file descriptors with os.dup() before wrapping in TextIOWrapper. Without this, closing the wrapper also closes sys.stdin.buffer / sys.stdout.buffer, breaking any subsequent stdio operations in the caller process. Fixes modelcontextprotocol#1933
|
Closing as a duplicate of #2040, which uses the closefd=False approach discussed in review there. Thanks for the contribution. |
Sorry, something went wrong.
| Back | FazBrowse Home | New Git URL |
Summary
Fixes #1933
stdio_server() wraps sys.stdin.buffer / sys.stdout.buffer in TextIOWrapper. When the server exits, these wrappers close the underlying binary streams, which also closes the real process stdin/stdout. Any subsequent print() or input() in the caller raises ValueError: I/O operation on closed file.
Root cause
TextIOWrapper.__exit__ closes the wrapped buffer. When that buffer is sys.stdin.buffer, the close propagates to the real file descriptor.
Fix
Use os.dup() to duplicate the file descriptors before wrapping. Closing the wrapper now only closes the duplicate, leaving the original process handles intact.
When stdin/stdout lack real file descriptors (e.g. io.BytesIO in tests), fall back to the original behavior.
Changes