Skip to content

Commit b3c713a

Browse files
authored
pythongh-140482: Preserve and restore stty echo as a test environment (python#140519)
pythongh-140482: Restore `stty echo` as a test environment
1 parent 44b6eea commit b3c713a

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Lib/test/libregrtest/save_env.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@
99

1010
from .utils import print_warning
1111

12+
# Import termios to save and restore terminal echo. This is only available on
13+
# Unix, and it's fine if the module can't be found.
14+
try:
15+
import termios # noqa: F401
16+
except ModuleNotFoundError:
17+
pass
18+
1219

1320
class SkipTestEnvironment(Exception):
1421
pass
@@ -65,6 +72,7 @@ def __init__(self, test_name, verbose, quiet, *, pgo):
6572
'shutil_archive_formats', 'shutil_unpack_formats',
6673
'asyncio.events._event_loop_policy',
6774
'urllib.requests._url_tempfiles', 'urllib.requests._opener',
75+
'stty_echo',
6876
)
6977

7078
def get_module(self, name):
@@ -292,6 +300,24 @@ def restore_warnings_showwarning(self, fxn):
292300
warnings = self.get_module('warnings')
293301
warnings.showwarning = fxn
294302

303+
def get_stty_echo(self):
304+
termios = self.try_get_module('termios')
305+
if not os.isatty(fd := sys.__stdin__.fileno()):
306+
return None
307+
attrs = termios.tcgetattr(fd)
308+
lflags = attrs[3]
309+
return bool(lflags & termios.ECHO)
310+
def restore_stty_echo(self, echo):
311+
termios = self.get_module('termios')
312+
attrs = termios.tcgetattr(fd := sys.__stdin__.fileno())
313+
if echo:
314+
# Turn echo on.
315+
attrs[3] |= termios.ECHO
316+
else:
317+
# Turn echo off.
318+
attrs[3] &= ~termios.ECHO
319+
termios.tcsetattr(fd, termios.TCSADRAIN, attrs)
320+
295321
def resource_info(self):
296322
for name in self.resources:
297323
method_suffix = name.replace('.', '_')
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Preserve and restore the state of ``stty echo`` as part of the test environment.

0 commit comments

Comments
 (0)