Computer Science Atlas
Code Review

Python 3 Examples: Write to stdout and stderr

February 4, 2021
 

Table of Contents

Using print

Writing to Standard Output (stdout) using print is simple:

Copy
print( "Hello Standard Output!" )
1
print( "Hello Standard Output!" )

But if you want to write to Standard Error (stderr), you'll have to import the sys library:

Copy
import sys

print( "Hello Standard Error!", file=sys.stderr )
1
2
3
import sys

print( "Hello Standard Error!", file=sys.stderr )

Using write

You can also write to stdout or stderr using the sys.stdout and sys.stderr file objects:

Copy
import sys

sys.stdout.write( "Hello Standard Output!\n" )
sys.stderr.write( "Hello Standard Error!\n" )
1
2
3
4
import sys

sys.stdout.write( "Hello Standard Output!\n" )
sys.stderr.write( "Hello Standard Error!\n" )

Whereas print automatically adds a newline character \n at the end, with sys.stdout.write and sys.stderr.write, you need to explicitly add it.

References