sys.stderr.write and sys.exit

Ben Finney bignose+hates-spam at benfinney.id.au
Thu Nov 23 17:39:10 EST 2006


"GinTon" <jonas.esp at googlemail.com> writes:

> Is the same use _sys.stderr.write('error message'); sys.exit(1)_
> than _sys.exit('error message')_ ?

(Note: The underscore '_' is a valid character in Python code, so I
was quite confused by what you wrote and had to read it several times
to see that you were intending the underscores not to be part of the
code. Better to show a line of code on its own line in your message.)

Code that wants to catch SystemExit will get a different exception
object in each case::

    >>> import sys
    >>> from StringIO import StringIO
    >>> sys.stderr = StringIO()

    >>> try:
    ...     sys.stderr.write('error message')
    ...     sys.exit(1)
    ... except SystemExit, e:
    ...     print "stderr contains:", sys.stderr.getvalue()
    ...     print "e.code is:", e.code
    ...
    stderr contains: error message
    e.code is: 1

    >>> try:
    ...     sys.exit('error message')
    ... except SystemExit, e:
    ...     print "stderr contains:", sys.stderr.getvalue()
    ...     print "e.code is:", e.code
    ...
    stderr contains: error message
    e.code is: error message

I quite often catch SystemExit in unit tests, or other code that is
inspecting a program module.

-- 
 \      "I have a large seashell collection, which I keep scattered on |
  `\        the beaches all over the world. Maybe you've seen it."  -- |
_o__)                                                    Steven Wright |
Ben Finney




More information about the Python-list mailing list