Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
bb60653
gh-138577: Fix keyboard shortcuts in getpass with echo_char
CuriousLearner Nov 15, 2025
31e35e4
Address reviews on dispatcher pattern + handle other ctrl chars
CuriousLearner Nov 16, 2025
b8609bd
Address reviews
CuriousLearner Nov 30, 2025
2691ad9
Merge remote-tracking branch 'upstream/main' into fix-gh-138577
CuriousLearner Mar 21, 2026
6a59f3b
Address reviews
CuriousLearner Mar 22, 2026
d280ce9
fix: prevent prompt corruption during getpass echo_char line editing
CuriousLearner Mar 23, 2026
3f1a861
fix: disable IEXTEN in non-canonical mode to allow Ctrl+V (LNEXT) han…
CuriousLearner Mar 23, 2026
537392c
refactor: address review on getpass echo_char line editing
CuriousLearner Mar 23, 2026
e1e4aa3
fix: Add comments about ICANON and IEXTEN
CuriousLearner Mar 23, 2026
3e05fa3
Merge branch 'main' of github.com:python/cpython into fix-gh-138577
CuriousLearner Mar 23, 2026
90da605
Address reviews
CuriousLearner Mar 24, 2026
ef1efcb
Merge branch 'main' into fix-gh-138577
CuriousLearner Mar 24, 2026
a7c1de3
Remove prefix from private class methods
CuriousLearner Mar 24, 2026
78b2c6a
Merge branch 'fix-gh-138577' of github.com:CuriousLearner/cpython int…
CuriousLearner Mar 24, 2026
e1461a7
Merge branch 'main' of github.com:python/cpython into fix-gh-138577
CuriousLearner Mar 24, 2026
741a817
Apply suggestions from code review
vstinner Mar 24, 2026
cc5dc99
chore! update some documentation
picnixz Mar 29, 2026
0f5f5c8
fix! refresh screen on Ctrl+A/Ctrl-E
picnixz Mar 29, 2026
9d90dfa
refactor! use more handlers
picnixz Mar 29, 2026
3b2ae38
chore! reduce diff against `main`
picnixz Mar 29, 2026
919af5c
test: add cursor position tests for Ctrl+A/Ctrl+E in getpass echo_char
CuriousLearner Mar 30, 2026
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
20 changes: 17 additions & 3 deletions Doc/library/getpass.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,27 @@ The :mod:`getpass` module provides two functions:
On Unix systems, when *echo_char* is set, the terminal will be
configured to operate in
:manpage:`noncanonical mode <termios(3)#Canonical_and_noncanonical_mode>`.
In particular, this means that line editing shortcuts such as
:kbd:`Ctrl+U` will not work and may insert unexpected characters into
the input.
Common terminal control characters are supported:

* :kbd:`Ctrl+A` - Move cursor to beginning of line
* :kbd:`Ctrl+E` - Move cursor to end of line
* :kbd:`Ctrl+K` - Kill (delete) from cursor to end of line
* :kbd:`Ctrl+U` - Kill (delete) entire line
* :kbd:`Ctrl+W` - Erase previous word
* :kbd:`Ctrl+V` - Insert next character literally (quote)
* :kbd:`Backspace`/:kbd:`DEL` - Delete character before cursor

These shortcuts work by reading the terminal's configured control
character mappings from termios settings.

.. versionchanged:: 3.14
Added the *echo_char* parameter for keyboard feedback.

.. versionchanged:: 3.15
Comment thread
vstinner marked this conversation as resolved.
Outdated
When using *echo_char* on Unix, keyboard shortcuts (including cursor
Comment thread
vstinner marked this conversation as resolved.
Outdated
movement and line editing) are now properly handled using the terminal's
control character configuration.

.. exception:: GetPassWarning

A :exc:`UserWarning` subclass issued when password input may be echoed.
Expand Down
199 changes: 175 additions & 24 deletions Lib/getpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,40 @@
class GetPassWarning(UserWarning): pass


# Default POSIX control character mappings
_POSIX_CTRL_CHARS = {
Comment thread
vstinner marked this conversation as resolved.
Outdated
'ERASE': '\x7f', # DEL/Backspace
'KILL': '\x15', # Ctrl+U - kill line
'WERASE': '\x17', # Ctrl+W - erase word
'LNEXT': '\x16', # Ctrl+V - literal next
'EOF': '\x04', # Ctrl+D - EOF
'INTR': '\x03', # Ctrl+C - interrupt
'SOH': '\x01', # Ctrl+A - start of heading (beginning of line)
'ENQ': '\x05', # Ctrl+E - enquiry (end of line)
'VT': '\x0b', # Ctrl+K - vertical tab (kill forward)
}


def _get_terminal_ctrl_chars(fd):
"""Extract control characters from terminal settings.

Returns a dict mapping control char names to their str values.
Falls back to POSIX defaults if termios isn't available.
"""
res = _POSIX_CTRL_CHARS.copy()
Comment thread
vstinner marked this conversation as resolved.
Outdated
try:
old = termios.tcgetattr(fd)
cc = old[6] # Index 6 is the control characters array
except (termios.error, OSError):
return res
# Ctrl+A/E/K are not in termios, use POSIX defaults
Comment thread
vstinner marked this conversation as resolved.
Outdated
Comment thread
vstinner marked this conversation as resolved.
Outdated
for name in ('ERASE', 'KILL', 'WERASE', 'LNEXT', 'EOF', 'INTR'):
cap = getattr(termios, f'V{name}')
if cap < len(cc):
res[name] = cc[cap].decode('latin-1')
return res


def unix_getpass(prompt='Password: ', stream=None, *, echo_char=None):
"""Prompt for a password, with echo turned off.

Expand Down Expand Up @@ -73,15 +107,19 @@ def unix_getpass(prompt='Password: ', stream=None, *, echo_char=None):
old = termios.tcgetattr(fd) # a copy to save
new = old[:]
new[3] &= ~termios.ECHO # 3 == 'lflags'
# Extract control characters before changing terminal mode
term_ctrl_chars = None
if echo_char:
new[3] &= ~termios.ICANON
Comment thread
vstinner marked this conversation as resolved.
term_ctrl_chars = _get_terminal_ctrl_chars(fd)
tcsetattr_flags = termios.TCSAFLUSH
if hasattr(termios, 'TCSASOFT'):
tcsetattr_flags |= termios.TCSASOFT
try:
termios.tcsetattr(fd, tcsetattr_flags, new)
passwd = _raw_input(prompt, stream, input=input,
echo_char=echo_char)
echo_char=echo_char,
term_ctrl_chars=term_ctrl_chars)

finally:
termios.tcsetattr(fd, tcsetattr_flags, old)
Expand Down Expand Up @@ -159,7 +197,8 @@ def _check_echo_char(echo_char):
f"character, got: {echo_char!r}")


def _raw_input(prompt="", stream=None, input=None, echo_char=None):
def _raw_input(prompt="", stream=None, input=None, echo_char=None,
term_ctrl_chars=None):
# This doesn't save the string in the GNU readline history.
if not stream:
stream = sys.stderr
Expand All @@ -177,7 +216,8 @@ def _raw_input(prompt="", stream=None, input=None, echo_char=None):
stream.flush()
# NOTE: The Python C API calls flockfile() (and unlock) during readline.
if echo_char:
return _readline_with_echo_char(stream, input, echo_char)
return _readline_with_echo_char(stream, input, echo_char,
term_ctrl_chars)
line = input.readline()
if not line:
raise EOFError
Expand All @@ -186,33 +226,144 @@ def _raw_input(prompt="", stream=None, input=None, echo_char=None):
return line


def _readline_with_echo_char(stream, input, echo_char):
passwd = ""
eof_pressed = False
class _PasswordLineEditor:
"""Handles line editing for password input with echo character."""

def __init__(self, stream, echo_char, ctrl_chars):
self.stream = stream
self.echo_char = echo_char
self.passwd = ""
Comment thread
vstinner marked this conversation as resolved.
Outdated
self.cursor_pos = 0
self.eof_pressed = False
self.literal_next = False
self.ctrl = ctrl_chars
self._dispatch = {
ctrl_chars['SOH']: self._handle_move_start, # Ctrl+A
ctrl_chars['ENQ']: self._handle_move_end, # Ctrl+E
ctrl_chars['VT']: self._handle_kill_forward, # Ctrl+K
ctrl_chars['KILL']: self._handle_kill_line, # Ctrl+U
ctrl_chars['WERASE']: self._handle_erase_word, # Ctrl+W
ctrl_chars['ERASE']: self._handle_erase, # DEL
'\b': self._handle_erase, # Backspace
}

def _refresh_display(self):
"""Redraw the entire password line with *echo_char*."""
self.stream.write('\r' + ' ' * len(self.passwd) + '\r')
self.stream.write(self.echo_char * len(self.passwd))
if self.cursor_pos < len(self.passwd):
self.stream.write('\b' * (len(self.passwd) - self.cursor_pos))
self.stream.flush()

def _erase_chars(self, count):
"""Erase count echo characters from display."""
Comment thread
vstinner marked this conversation as resolved.
Outdated
self.stream.write("\b \b" * count)

def _insert_char(self, char):
"""Insert character at cursor position."""
Comment thread
vstinner marked this conversation as resolved.
Outdated
self.passwd = self.passwd[:self.cursor_pos] + char + self.passwd[self.cursor_pos:]
self.cursor_pos += 1
# Only refresh if inserting in middle
if self.cursor_pos < len(self.passwd):
self._refresh_display()
else:
self.stream.write(self.echo_char)
self.stream.flush()

def _handle_move_start(self):
"""Move cursor to beginning (Ctrl+A)."""
self.cursor_pos = 0

def _handle_move_end(self):
"""Move cursor to end (Ctrl+E)."""
self.cursor_pos = len(self.passwd)

def _handle_erase(self):
"""Delete character before cursor (Backspace/DEL)."""
if self.cursor_pos > 0:
Comment thread
vstinner marked this conversation as resolved.
Outdated
self.passwd = self.passwd[:self.cursor_pos-1] + self.passwd[self.cursor_pos:]
Comment thread
vstinner marked this conversation as resolved.
Outdated
self.cursor_pos -= 1
# Only refresh if deleting from middle
if self.cursor_pos < len(self.passwd):
self._refresh_display()
else:
self.stream.write("\b \b")
self.stream.flush()

def _handle_kill_line(self):
"""Erase entire line (Ctrl+U)."""
self._erase_chars(len(self.passwd))
self.passwd = ""
self.cursor_pos = 0
self.stream.flush()

def _handle_kill_forward(self):
"""Kill from cursor to end (Ctrl+K)."""
chars_to_delete = len(self.passwd) - self.cursor_pos
self.passwd = self.passwd[:self.cursor_pos]
self._erase_chars(chars_to_delete)
self.stream.flush()

def _handle_erase_word(self):
"""Erase previous word (Ctrl+W)."""
old_cursor = self.cursor_pos
# Skip trailing spaces
while self.cursor_pos > 0 and self.passwd[self.cursor_pos-1] == ' ':
self.cursor_pos -= 1
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can actually skip the trailing spaces as follows:

stripped = self.passwd.rstrip(' ')
self.cursor_pos = self.cursor_pos - (len(self.passwd) - len(stripped))

# Delete the word
while self.cursor_pos > 0 and self.passwd[self.cursor_pos-1] != ' ':
self.cursor_pos -= 1
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here, use str.rfind using the start of the new cursor position.

# Remove the deleted portion
self.passwd = self.passwd[:self.cursor_pos] + self.passwd[old_cursor:]
self._refresh_display()

def handle(self, char):
"""Handle a single character input. Returns True if handled."""
self.eof_pressed = False
handler = self._dispatch.get(char)
if handler:
handler()
return True
return False


def _readline_with_echo_char(stream, input, echo_char, term_ctrl_chars=None):
"""Read password with echo character and line editing support."""
if term_ctrl_chars is None:
term_ctrl_chars = _POSIX_CTRL_CHARS.copy()
Comment thread
vstinner marked this conversation as resolved.
Outdated

editor = _PasswordLineEditor(stream, echo_char, term_ctrl_chars)

while True:
Comment thread
vstinner marked this conversation as resolved.
Outdated
char = input.read(1)
if char == '\n' or char == '\r':

# Check for line terminators
if char in ('\n', '\r'):
break
elif char == '\x03':
# Handle literal next mode FIRST (Ctrl+V quotes next char)
elif editor.literal_next:
editor._insert_char(char)
editor.literal_next = False
editor.eof_pressed = False
# Check if it's the LNEXT character
elif char == editor.ctrl['LNEXT']:
editor.literal_next = True
editor.eof_pressed = False
# Check for special control characters
elif char == editor.ctrl['INTR']:
raise KeyboardInterrupt
elif char == '\x7f' or char == '\b':
if passwd:
stream.write("\b \b")
stream.flush()
passwd = passwd[:-1]
elif char == '\x04':
if eof_pressed:
elif char == editor.ctrl['EOF']:
if editor.eof_pressed:
break
else:
eof_pressed = True
editor.eof_pressed = True
elif char == '\x00':
continue
else:
passwd += char
stream.write(echo_char)
stream.flush()
eof_pressed = False
return passwd
pass
# Dispatch to handler or insert as normal character
elif not editor.handle(char):
editor._insert_char(char)
editor.eof_pressed = False
Comment thread
vstinner marked this conversation as resolved.
Outdated

return editor.passwd


def getuser():
Expand Down
Loading
Loading