diff --git a/Lib/_pyrepl/readline.py b/Lib/_pyrepl/readline.py index 4232a868a34e9a..751be254c73aa8 100644 --- a/Lib/_pyrepl/readline.py +++ b/Lib/_pyrepl/readline.py @@ -349,19 +349,13 @@ def do(self) -> None: @dataclass(slots=True) class _ReadlineWrapper: - f_in: int = -1 - f_out: int = -1 + f_in: int = 0 + f_out: int = 1 reader: ReadlineAlikeReader | None = field(default=None, repr=False) saved_history_length: int = -1 startup_hook: Callback | None = None config: ReadlineConfig = field(default_factory=ReadlineConfig, repr=False) - def __post_init__(self) -> None: - if self.f_in == -1: - self.f_in = os.dup(0) - if self.f_out == -1: - self.f_out = os.dup(1) - def get_reader(self) -> ReadlineAlikeReader: if self.reader is None: console = Console(self.f_in, self.f_out, encoding=ENCODING) diff --git a/Lib/test/test_pyrepl/test_pyrepl.py b/Lib/test/test_pyrepl/test_pyrepl.py index 1828fd735669d5..d5dd960b40f6a2 100644 --- a/Lib/test/test_pyrepl/test_pyrepl.py +++ b/Lib/test/test_pyrepl/test_pyrepl.py @@ -25,7 +25,7 @@ ) from test.support import has_subprocess_support, SHORT_TIMEOUT, STDLIB_DIR from test.support.import_helper import import_module -from test.support.os_helper import EnvironmentVarGuard, unlink +from test.support.os_helper import EnvironmentVarGuard, fd_count, unlink from .support import ( FakeConsole, @@ -2723,3 +2723,24 @@ def test_exact_width_line_does_not_wrap(self): console, wc = self._make_mock_console(width=width) self._apply_changed_line(console, wc, y, "", "a" * width) self.assertEqual(console.posxy, (width - 1, y)) + + +@skipUnless(hasattr(os, "openpty"), "need os.openpty()") +class TestReadlineWrapperFileDescriptors(TestCase): + def test_reader_does_not_open_file_descriptors(self): + controller, worker = os.openpty() + self.addCleanup(os.close, controller) + self.addCleanup(os.close, worker) + env = self.enterContext(EnvironmentVarGuard()) + env["TERM"] = "ansi" + sys.stdout.flush() + for fd in (0, 1): + saved = os.dup(fd) + self.addCleanup(os.close, saved) + self.addCleanup(os.dup2, saved, fd) + os.dup2(worker, fd) + + before = fd_count() + wrapper = _ReadlineWrapper() + wrapper.get_reader() + self.assertEqual(fd_count(), before) diff --git a/Misc/NEWS.d/next/Library/2026-11-07-16-01-33.gh-issue-161549.rKq8Lw.rst b/Misc/NEWS.d/next/Library/2026-11-07-16-01-33.gh-issue-161549.rKq8Lw.rst new file mode 100644 index 00000000000000..e2927404fb2530 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-07-16-01-33.gh-issue-161549.rKq8Lw.rst @@ -0,0 +1,2 @@ +Fix a file descriptor leak when :mod:`!_pyrepl.readline` is re-imported in +a terminal.