In this lesson, I’ll show you how to print the value to standard error (STDERR) or standard output (STDOUT) in Python.
The print statement and function will check whether a value is a string and display it, otherwise, it converts it to a string first.
STDOUT in Python 2
You can use the print statement to the standard output indicating that in the code, but you can also use just print and value will be printed to standard output by default.
import sys a = 11 print >> sys.stdout, a print >> sys.stdout, "This is standard output" print a print "This is also standard output "
This will give us the following result.
None of these statements return error with the int value, because print it works as a wrapper that automatically converts a value to a string.
STDERR in Python 2
If you try to print a message to standard error and then print a message to standard output, the first message displayed in a console will be standard output and the second standard error, even if STDERR is first in code.
import sys a = 11 print >> sys.stderr, a print >> sys.stderr, "This error message" print a print "This print message"
STDOUT in Python 3
The previous code won’t work in Python 3, because print there is a function and not a statement.
In Python 3, you can indicate stdout as the second parameter of the print function.
import sys a = 11 print(a) print(a, file=sys.stdout)
This code will return 11 twice.
In Python 3, you can also use the write function to write to standard output.
import sys a = 11 print(a) print(a, file=sys.stdout) sys.stdout.write(a)
This code will return the following result.
The write function returned an error, because it doesn’t convert non-string values to string as print does.
If you change the variable from int to string, all messages will return text to standard output.
import sys print("This is print function") print("This is print with the stdout as a parameter", file=sys.stdout) sys.stdout.write("Thins is write function")
The code will return this result every time it executes.
STDERR in Python 3
Modify the code, by changing STDOUT to STDERR.
import sys print("This is print function") print("This is print with the stdout as a parameter", file=sys.stderr) sys.stderr.write("Thins is write function")
Run it and check the results. It can give you different output each time you run it.
This means that the standard error messages are sometimes executed before other parts of code and sometimes after code.
In the third example, you can see that both messages are displayed in one code. This happened because the write function doesn’t print the new line as print does.