Computer Science Atlas
Snippets

Python 3: Write to stdout and stderr

February 4, 2021
 
Table of Contents

Using print

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

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

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

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:

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