Reputation: 6707
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.
Upvotes: 2
Views: 6517
Reputation: 12971
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)
Upvotes: 4
Reputation: 881873
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.
Upvotes: 4