Skip to content

Commit d3a3a58

Browse files
committed
Properly print prompt to stderr when err=True is passed
The prompt was still printed to stdout, even when err=True was passed. Use redirect_stdout to fix this. Also, update the tests to test for the new behavior.
1 parent 909ebbf commit d3a3a58

2 files changed

Lines changed: 10 additions & 4 deletions

File tree

src/click/termui.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import sys
88
import typing as t
99
from contextlib import AbstractContextManager
10+
from contextlib import redirect_stdout
1011
from gettext import gettext as _
1112

1213
from ._compat import isatty
@@ -147,7 +148,11 @@ def prompt_func(text: str) -> str:
147148
else:
148149
# On non-Windows platforms, pass the full prompt to readline
149150
# so it can properly handle line editing and cursor positioning
150-
return f(text)
151+
if err:
152+
with redirect_stdout(sys.stderr):
153+
return f(text)
154+
else:
155+
return f(text)
151156
except (KeyboardInterrupt, EOFError):
152157
# getpass doesn't print a newline if the user aborts input with ^C.
153158
# Allegedly this behavior is inherited from getpass(3).

tests/test_utils.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,8 @@ def f(_):
227227
click.echo("interrupted")
228228

229229
out, err = capsys.readouterr()
230-
assert out == "Password:\ninterrupted\n"
230+
# On non-Windows, prompt is passed directly to getpass, not echoed separately
231+
assert out == "\ninterrupted\n"
231232

232233

233234
def test_prompts_eof(runner):
@@ -484,8 +485,8 @@ def emulate_input(text):
484485
emulate_input("asdlkj\n")
485486
click.prompt("Prompt to stderr", err=True)
486487
out, err = capfd.readouterr()
487-
assert out == " "
488-
assert err == "Prompt to stderr:"
488+
assert out == ""
489+
assert err == "Prompt to stderr: "
489490

490491
emulate_input("y\n")
491492
click.confirm("Prompt to stdin")

0 commit comments

Comments
 (0)