Skip to content

Commit 2c96fe2

Browse files
Stop preferring a TTY output when creating the default output.
Use PlainTextOutput instead if `sys.stdout` is not a TTY. Especially for printing formatted text, it is useful for the output to be redirected to a file. In that case, we don't want to include ANSI escape sequences, but have a plain text output. Similar to how we can read input from something that was piped into stdin.
1 parent 402b6a3 commit 2c96fe2

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

prompt_toolkit/output/defaults.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,24 +10,29 @@
1010

1111
from .base import DummyOutput, Output
1212
from .color_depth import ColorDepth
13+
from .plain_text import PlainTextOutput
1314

1415
__all__ = [
1516
"create_output",
1617
]
1718

1819

1920
def create_output(
20-
stdout: Optional[TextIO] = None, always_prefer_tty: bool = True
21+
stdout: Optional[TextIO] = None, always_prefer_tty: bool = False
2122
) -> Output:
2223
"""
2324
Return an :class:`~prompt_toolkit.output.Output` instance for the command
2425
line.
2526
2627
:param stdout: The stdout object
2728
:param always_prefer_tty: When set, look for `sys.stderr` if `sys.stdout`
28-
is not a TTY. (The prompt_toolkit render output is not meant to be
29-
consumed by something other then a terminal, so this is a reasonable
30-
default.)
29+
is not a TTY. Useful if `sys.stdout` is redirected to a file, but we
30+
still want user input and output on the terminal.
31+
32+
By default, this is `False`. If `sys.stdout` is not a terminal (maybe
33+
it's redirected to a file), then a `PlainTextOutput` will be returned.
34+
That way, tools like `print_formatted_text` will write plain text into
35+
that file.
3136
"""
3237
# Consider TERM, PROMPT_TOOLKIT_BELL, and PROMPT_TOOLKIT_COLOR_DEPTH
3338
# environment variables. Notice that PROMPT_TOOLKIT_COLOR_DEPTH value is
@@ -82,6 +87,12 @@ def create_output(
8287
else:
8388
from .vt100 import Vt100_Output
8489

90+
# Stdout is not a TTY? Render as plain text.
91+
# This is mostly useful if stdout is redirected to a file, and
92+
# `print_formatted_text` is used.
93+
if not stdout.isatty():
94+
return PlainTextOutput(stdout)
95+
8596
return Vt100_Output.from_pty(
8697
stdout,
8798
term=term_from_env,

0 commit comments

Comments
 (0)