Skip to content

Commit 051b9e4

Browse files
committed
revisit stdin/stdout/stderr handling
Reverts/changes 3ff3cfa. Unfortunately the example at pytest-dev/pytest#5134 appears to be for py2 - at least it did not compile for me when trying it.
1 parent 4a1f0be commit 051b9e4

File tree

1 file changed

+28
-19
lines changed

1 file changed

+28
-19
lines changed

pyrepl/readline.py

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -189,22 +189,30 @@ class _ReadlineWrapper(object):
189189
saved_history_length = -1
190190
startup_hook = None
191191
config = ReadlineConfig()
192-
stdin = None
193-
stdout = None
194-
stderr = None
195192

196-
def __init__(self, f_in=None, f_out=None):
197-
self.f_in = f_in if f_in is not None else os.dup(0)
198-
self.f_out = f_out if f_out is not None else os.dup(1)
193+
# Forced input/output, otherwise sys.stdin/sys.stdout will be used.
194+
f_in = None
195+
f_out = None
199196

200-
def setup_std_streams(self, stdin, stdout, stderr):
201-
self.stdin = stdin
202-
self.stdout = stdout
203-
self.stderr = stderr
197+
def __init__(self, f_in=None, f_out=None):
198+
if f_in is not None:
199+
self.f_in = f_in
200+
if f_out is not None:
201+
self.f_out = f_out
204202

205203
def get_reader(self):
206-
if self.reader is None:
207-
console = UnixConsole(self.f_in, self.f_out, encoding=ENCODING)
204+
if self.f_in is None:
205+
fd_in = sys.stdin.fileno()
206+
else:
207+
fd_in = self.f_in
208+
if self.f_out is None:
209+
fd_out = sys.stdout.fileno()
210+
else:
211+
fd_out = self.f_out
212+
if (self.reader is None
213+
or fd_in != self.reader.console.input_fd
214+
or fd_out != self.reader.console.output_fd):
215+
console = UnixConsole(fd_in, fd_out, encoding=ENCODING)
208216
self.reader = ReadlineAlikeReader(console)
209217
self.reader.config = self.config
210218
return self.reader
@@ -221,10 +229,14 @@ def raw_input(self, prompt=''):
221229
# behavior: it seems to be the correct thing to do, and moreover it
222230
# mitigates this pytest issue:
223231
# https://github.com/pytest-dev/pytest/issues/5134
224-
if self.stdout and hasattr(self.stdout, 'flush'):
225-
self.stdout.flush()
226-
if self.stderr and hasattr(self.stderr, 'flush'):
227-
self.stderr.flush()
232+
try:
233+
sys.stdout.flush()
234+
except AttributeError:
235+
pass
236+
try:
237+
sys.stderr.flush()
238+
except AttributeError:
239+
pass
228240

229241
ret = reader.readline(startup_hook=self.startup_hook)
230242
if not PY3:
@@ -447,9 +459,6 @@ def _setup():
447459
if not os.isatty(f_in) or not os.isatty(f_out):
448460
return
449461

450-
_wrapper.f_in = f_in
451-
_wrapper.f_out = f_out
452-
_wrapper.setup_std_streams(sys.stdin, sys.stdout, sys.stderr)
453462

454463
if '__pypy__' in sys.builtin_module_names: # PyPy
455464

0 commit comments

Comments
 (0)