Explain Codes LogoExplain Codes Logo

How do I print to stderr in Python?

python
error-handling
logging
stderr
Nikita BarsukovbyNikita Barsukov·Nov 10, 2024
TLDR

To print to stderr, use the sys module in Python. You can write directly with sys.stderr.write('Error Alert\n'), or for more formatting control, use print('Error Alert', file=sys.stderr). Make sure to include \n for line breaks if you use write.

import sys sys.stderr.write('Oops! An error.\n') print('Oops! An error.', file=sys.stderr)

Creating a Custom Function for Error Printing

To make your life easier when dealing with error messages, create a special function for this. We'll call this eprint (the "e" is for "error").

Defining eprint

Write this once, use it forever.

import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) # basically "print", but edgier

Using eprint

It's like a regular print, but in red (not really, but let's pretend).

eprint("Error:", "It's not you, it's me.", sep=" - ")

This will print: "Error: - It's not you, it's me." to stderr.

How eprint Enhances Error Handling

In situations where you need to log an unusual condition or error message, eprint becomes your new best friend.

Proper handling of '\n'

When using sys.stderr.write(), remember to tuck in a '\n' for the message to have a good night's sleep (i.e., line break). The print function takes care of this automatically, so no need to be a helicopter parent.

Using the 'future' features (Yeah, Python is ahead of time)

If your code is in Python 2 but you're afraid of being left in the past, import print_function from __future__.

from __future__ import print_function # living in the future! 🚀

This tells Python 2 to use the Python 3 print function. This way, you avoid the outdated print >> sys.stderr, "message" syntax.

Making Erroneous Situations More Entertaining with Jokes

Go for Direct Writing for Maximum Thrills

If living on the edge is your thing or if you need maximum performance, write directly to stderr.

sys.stderr.write("'What's up, doc?' - Bugs Bunny, probably\n")

Starting Python 3, the print function got a major upgrade: redirecting its output to stderr directly.

print("Don't you wish your print function was versatile like me?", file=sys.stderr) # showing off new skills

Professional Error Tracking with Logging

Basic setup with the logging module

With Python's logging module, you can go professional and ditch the primitive ways of error tracking.

import logging logging.basicConfig(level=logging.ERROR, format='%(levelname)s: %(message)s') logger = logging.getLogger('my_logger') # my_logger, sounds professional!

Use logger.error("An error clearly happened") to write an error message to stderr.

Using logging for warnings without spamming stdout

Sometimes, non-critical errors occur. They're like when your pet misbehaves: not an immediate crisis, but you'd wish they hadn't done it. Use log.warning() to handle these minor disturbances.

logger.warning('This is the "your pet peed on the floor again" kind of warning') # 😼 mischief!

These warnings get sent to stderr, leaving your stdout clean and beautiful.

Advanced stderr Outputs

Direct writing to stderr with os.write()

For more control over the output, use os.write(), which writes directly to a file descriptor.

import os os.write(2, b'This one goes straight to stderr! \n') # sending secret messages

Remember to specify 2 as the first parameter, since that's the file descriptor for stderr.

Prioritizing compatibility

Even if you're in Python 2, use methods compatible with Python 3 for a smooth transition in the future.

import sys if sys.version_info[0] < 3: from __future__ import print_function # ensures Python 2 behaves like Python 3