Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d5aa487

Browse files
committed
#21169: fix getpass to use replace error handler on UnicodeEncodeError.
If the input stream encoding couldn't encode one or more of the non-ascii characters in the prompt, it would fail, throwing a UnicodeEncodeError. Now if that happens we re-encoding using the 'replace' error handler. Patch by Kushal Das.
1 parent e544f9a commit d5aa487

3 files changed

Lines changed: 19 additions & 2 deletions

File tree

Lib/getpass.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,12 @@ def _raw_input(prompt="", stream=None, input=None):
135135
input = sys.stdin
136136
prompt = str(prompt)
137137
if prompt:
138-
stream.write(prompt)
138+
try:
139+
stream.write(prompt)
140+
except UnicodeEncodeError:
141+
prompt = prompt.encode(stream.encoding, 'replace')
142+
prompt = prompt.decode(stream.encoding)
143+
stream.write(prompt)
139144
stream.flush()
140145
# NOTE: The Python C API calls flockfile() (and unlock) during readline.
141146
line = input.readline()

Lib/test/test_getpass.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import getpass
22
import os
33
import unittest
4-
from io import BytesIO, StringIO
4+
from io import BytesIO, StringIO, TextIOWrapper
55
from unittest import mock
66
from test import support
77

@@ -69,6 +69,14 @@ def test_uses_stdin_as_default_input(self, mock_input):
6969
getpass._raw_input(stream=StringIO())
7070
mock_input.readline.assert_called_once_with()
7171

72+
@mock.patch('sys.stdin')
73+
def test_uses_stdin_as_different_locale(self, mock_input):
74+
stream = TextIOWrapper(BytesIO(), encoding="ascii")
75+
mock_input.readline.return_value = "Hasło: "
76+
getpass._raw_input(prompt="Hasło: ",stream=stream)
77+
mock_input.readline.assert_called_once_with()
78+
79+
7280
def test_raises_on_empty_input(self):
7381
input = StringIO('')
7482
self.assertRaises(EOFError, getpass._raw_input, input=input)

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ Core and Builtins
2727
Library
2828
-------
2929

30+
- Issue #21169: getpass now handles non-ascii characters that the
31+
input stream encoding cannot encode by re-encoding using the
32+
replace error handler.
33+
3034
- Issue #21171: Fixed undocumented filter API of the rot13 codec.
3135
Patch by Berker Peksag.
3236

0 commit comments

Comments
 (0)