Skip to content

Commit 37e885b

Browse files
committed
Add newline to new REPL output when needed to avoid having the prompt in the same line as last output.
1 parent 92e5f82 commit 37e885b

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

Lib/_pyrepl/console.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from abc import ABC, abstractmethod
2525
import ast
2626
import code
27+
import io
2728
from dataclasses import dataclass, field
2829
import os.path
2930
import sys
@@ -177,7 +178,19 @@ def _excepthook(self, typ, value, tb):
177178

178179
def runcode(self, code):
179180
try:
181+
temp_output = io.StringIO()
182+
old_stdout = sys.stdout
183+
sys.stdout = temp_output
180184
exec(code, self.locals)
185+
output = ""
186+
if hasattr(sys.stdout, "getvalue"):
187+
output = sys.stdout.getvalue()
188+
# Avoid restoring old stdout if it has been changed during exec
189+
if sys.stdout is temp_output:
190+
sys.stdout = old_stdout
191+
if not output.endswith("\n"):
192+
output += "\n"
193+
print(output, end="")
181194
except SystemExit:
182195
raise
183196
except BaseException:

Lib/test/test_pyrepl/test_pyrepl.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1344,6 +1344,16 @@ def test_keyboard_interrupt_after_isearch(self):
13441344
output, exit_code = self.run_repl(["\x12", "\x03", "exit"])
13451345
self.assertEqual(exit_code, 0)
13461346

1347+
def test_newline_after_print_ending_in_space(self):
1348+
commands = ("print('abcdefg' * 250 + 'Z', end=' ')\n"
1349+
"exit()\n")
1350+
output, exit_code = self.run_repl(commands)
1351+
self.assertEqual(exit_code, 0)
1352+
print(output)
1353+
self.assertIn("Z \r\n", output)
1354+
expected = "abcdefg" * 200 + "Z " + "\r\n"
1355+
self.assertIn(expected, output)
1356+
13471357
def test_prompt_after_help(self):
13481358
output, exit_code = self.run_repl(["help", "q", "exit"])
13491359

0 commit comments

Comments
 (0)