How to output to standard error (stderr)
Pass standard error “sys.stderr” as the “file” argument of the print function. The following sample program uses the print function to output a string to standard error.import sys
# Output to standard error (stderr)
print('An error has occurred.', file=sys.stderr)
If you use the write method of sys.stderr, it will look like this: unlike the print function, it does not automatically insert a newline, so we use ‘\n’ to output a newline.
import sys
# Output to standard error (stderr)
sys.stderr.write('An error has occurred.\n')
What is sys.stderr?
sys.stderr is a file object for reading and writing to standard error. For example, if you write to a file object that opens a text file, it writes the contents to that file. sys.stderr does not write to a file, it writes to standard error.What is stderr?
Standard error is a place where messages such as errors or warnings that occur during program execution are output. Normally, standard error is displayed on the screen such as console or terminal, but you can also redirect or pipe it to another location. You can separate the output destination by printing normal program operation to standard output and errors to standard error. For example, you can save standard output to a file and display standard errors on the screen.References
Test Environment
- Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]
- Microsoft Windows 10 Enterprise Version 22H2 OS Build 19045.2604 Experience: Windows Feature Experience Pack 120.2212.4190.0
- Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
- Microsoft Windows 10 Pro Version 1809 OS Build 17763.439