219 – Print to standard error#
You can print directly to standard error (sys.stderr) by using the parameter file that the built-in function print supports:
import sys
print("Hello, world!")
print("Bye!", file=sys.stderr)
The argument passed to file can be any file-like object and it defaults to sys.stdout.
By running the code above, stdout will show the following output:
Hello, world!"
And stderr will show the following output:
Bye!
If you run the code in a regular terminal, you’ll see both prints. To see the distinction, you can try redirecting stdout to a file to only see the message “Bye!”:
$ python streams.py > random_file.txt
Bye!
$ cat random_file.txt
Hello, world!