Print a message and newline to stdout or a file. This should be used instead of `print` because it provides better support for different data, files, and environments. Compared to `print`, this does the following: - Ensures that the output encoding is not misconfigured on Linux.
(
message: Any | None = None,
file: IO[Any] | None = None,
nl: bool = True,
err: bool = False,
color: bool | None = None,
)
| 190 | |
| 191 | |
| 192 | def echo( |
| 193 | message: Any | None = None, |
| 194 | file: IO[Any] | None = None, |
| 195 | nl: bool = True, |
| 196 | err: bool = False, |
| 197 | color: bool | None = None, |
| 198 | ) -> None: |
| 199 | """Print a message and newline to stdout or a file. This should be |
| 200 | used instead of `print` because it provides better support |
| 201 | for different data, files, and environments. |
| 202 | |
| 203 | Compared to `print`, this does the following: |
| 204 | |
| 205 | - Ensures that the output encoding is not misconfigured on Linux. |
| 206 | - Supports Unicode in the Windows console. |
| 207 | - Supports writing to binary outputs, and supports writing bytes |
| 208 | to text outputs. |
| 209 | - Supports colors and styles on Windows. |
| 210 | - Removes ANSI color and style codes if the output does not look |
| 211 | like an interactive terminal. |
| 212 | - Always flushes the output. |
| 213 | """ |
| 214 | if file is None: |
| 215 | if err: |
| 216 | file = _default_text_stderr() |
| 217 | else: |
| 218 | file = _default_text_stdout() |
| 219 | |
| 220 | # There are no standard streams attached to write to. For example, |
| 221 | # pythonw on Windows. |
| 222 | if file is None: |
| 223 | return |
| 224 | |
| 225 | # Convert non bytes/text into the native string type. |
| 226 | if message is not None and not isinstance(message, (str, bytes, bytearray)): |
| 227 | out: str | bytes | bytearray | None = str(message) |
| 228 | else: |
| 229 | out = message |
| 230 | |
| 231 | if nl: |
| 232 | out = out or "" |
| 233 | if isinstance(out, str): |
| 234 | out += "\n" |
| 235 | else: |
| 236 | out += b"\n" |
| 237 | |
| 238 | if not out: |
| 239 | file.flush() |
| 240 | return |
| 241 | |
| 242 | # If there is a message and the value looks like bytes, we manually |
| 243 | # need to find the binary stream and write the message in there. |
| 244 | # This is done separately so that most stream types will work as you |
| 245 | # would expect. Eg: you can write to StringIO for other cases. |
| 246 | if isinstance(out, (bytes, bytearray)): |
| 247 | binary_file = _find_binary_writer(file) |
| 248 | |
| 249 | if binary_file is not None: |
no test coverage detected
searching dependent graphs…