I want to print basic error messages from a script. They should have the name of the script (i.e. sys.argv[0]
) then the message, and should be printed to stderr. Is there an easy way to do this using the standard library?
I've written the below (inspired by this related answer) and put it in its own module so I can import it in my scripts, but I feel like there's a better way.
from __future__ import print_function
import sys
def print_error(*args, **kwargs):
"""Print script name and anything else to stderr."""
print_stderr(sys.argv[0] + ':', *args, file=sys.stderr, **kwargs)
The easiest way is to use logging
. First set its format to '%(pathname)s: %(message)s'
, then use logging.error()
to print. For example:
# Setup
import logging
logging.basicConfig(format='%(pathname)s: %(message)s')
# Print error
logging.error('Test error message')
Usage:
$ python3 test.py
test.py: Test error message
$ python3 ~/test.py
/home/wja/test.py: Test error message
See LogRecord attributes for more info about pathname
and other available info.