views:

80

answers:

2

Hi,

What is the best way (standard) to display an error to the user in Python (for example: bad syntax, invalid arguments, logic errors)?

The method should print the error in the standard error and exit the program.

+2  A: 

In small programs, I use something like this:

import sys

def error(message):
    sys.stderr.write("error: %s\n" % message)
    sys.exit(1)

For bigger tools, I use the logging package.

def error(message):
    logging.error('error: ', message)
    sys.exit(1)
leoluk
How can I use logging to output to standard error (I already use it to output to a file)? How can I separe both streams?
Yassin
`logging` writes to `stderr` by default; if you want to seperate the streams, look at this: http://docs.python.org/library/logging.html#logging-to-multiple-destinations
leoluk
How about `raise SystemExit` instead of `sys.exit`, seems a bit more pythonic to me.
Joe D
You forgot the newline in the `sys.stderr.write` call.
AndiDog
thanks, newline added; sys.exits allows to specify a return value
leoluk
+2  A: 

In Python 2, for example:

import sys
print>>sys.stderr, "Found", numerrs, "errors in the input."
sys.exit(1)

In Python 3 (or 2.6 or 2.7 with the from __future__ import print_function statement at the top of your module), print becomes a function and the syntax for "printing to standard error" is now

print("Found", numerrs, "errors in the input.", file=sys.stderr)

(a somewhat more friendly syntax than the strange >> needed in Python 2;-).

The (small) advantage of print versus (say) sys.stderr.write is that you get "all the modern conveniences": all parts of the error message are automatically turned into strings, they're output with space separators, and a line-end is output for you at the end (unless you specifically request otherwise). To use sys.stderr.write, you need to build the exact string to output, typically using string-formatting constructs -- not a big deal, of course, just a small matter of convenience.

logging is usually preferred, but not when you specifically want the error message to go to standard error, and to standard error only: logging offers many, many more possibilities (send messages of various severity, filter some, put some to files, and so on), but therefore it's inevitably a little bit more complex.

Alex Martelli