Piping the output of rich print to a file introduces unwanted newlines if the line is longer than what fits on the screen #4188
-
|
So my colleague recently noticed that the output of the print function includes multiple lines if it gets piped to a file e.g.
would produce 2 as there are really two lines in the file ... If we remove the import Is this something that can be configured? Or is it a bug? There are (correctly) no color control characters so that seems to work fine ... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
This is rich falling back to a default width when it can't see a real terminal. When you pipe or redirect, Quick confirmation of what's happening (rich 15.0.0): from rich.console import Console
c = Console()
print(c.is_terminal, c.width) # to a file this prints: False 80
c.print("X" * 200) # gets split into 80 + 80 + 40 with newlinesThree ways to stop it, pick whichever fits: 1. Use a Console and pass from rich.console import Console
console = Console()
console.print("X" * 200, soft_wrap=True) # stays a single 200-char line in the fileNote the module-level 2. Give the Console an explicit wide width so it never wraps: Console(width=10_000).print("X" * 200)3. Set the COLUMNS=500 python yourscript.py > out.txtI'd reach for Verified on rich 15.0.0: redirected to a file, the default emits the 200-char line as 80/80/40, and both |
Beta Was this translation helpful? Give feedback.
-
|
Thank you very much for the fast answer! I'm probably going with not using "from rich import print" and using it only explicitly via Console. Just as a note: I think its a bit counterintuitive to break with user expectations there e.g. I would never expect the standard "print" to insert line breaks when using pipes :/ |
Beta Was this translation helpful? Give feedback.
This is rich falling back to a default width when it can't see a real terminal. When you pipe or redirect,
sys.stdoutisn't a TTY, so the Console can't detect the width, defaults to 80 columns, and word-wraps anything longer, writing real newlines into the file.Quick confirmation of what's happening (rich 15.0.0):
Three ways to stop it, pick whichever fits:
1. Use a Console and pass
soft_wrap=True. This is the "print what I gave you, don't wrap or crop" switch: