Skip to content

gh-132962: _pyrepl: Prevent crash on Windows when stdout is redirected #135456

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Lib/_pyrepl/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
raise RuntimeError("Windows 10 TH2 or later required")
if not os.isatty(sys.stdin.fileno()):
raise OSError(errno.ENOTTY, "tty required", "stdin")
if sys.platform == "win32" and not os.isatty(sys.stdout.fileno()):
raise OSError(errno.ENOTTY, "tty required", "stdout")
from .simple_interact import check
if err := check():
raise RuntimeError(err)
Expand Down
32 changes: 32 additions & 0 deletions Lib/test/test_pyrepl/test_windows_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
raise unittest.SkipTest("test only relevant on win32")


import subprocess
from tempfile import TemporaryDirectory
import os
import itertools
from functools import partial
from test.support import force_not_colorized_test_class
Expand Down Expand Up @@ -577,5 +580,34 @@ def test_up_vt(self):
self.assertEqual(self.mock.call_count, 3)


class WindowsCommandLineTests(unittest.TestCase):
def test_for_crash_traceback_with_redirected_stdout(self):
"""python.bat -i -c "print('hlwd')" > file.txt"""
script_command = "print('script has run')"
with TemporaryDirectory() as tmp_dir:
stdout_path = os.path.join(tmp_dir, "WinCMDLineTests.txt")
with open(stdout_path, "w") as stdout_file, \
subprocess.Popen(
[sys.executable, '-i', '-c', script_command],
stdin=None,
stdout=stdout_file,
stderr=subprocess.PIPE,
text=True, errors='replace'
) as process:
stderr_output = ""
try:
process.wait(timeout=3)
except subprocess.TimeoutExpired:
process.kill()
_, stderr_output = process.communicate()
has_crash_traceback = (
"OSError" in stderr_output and
len(stderr_output) > 1200
)
if has_crash_traceback:
self.fail("Detected endless OSError traceback."
f"\n--- stderr ---\n{stderr_output[:1200]}")


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The interactive interpreter (-i) on Windows no longer crashes when standard
output is redirected. It now correctly falls back to the basic REPL in this
situation.
Loading